w0lf
w0lf

Reputation: 3

Cannot display correct format in Java

I am unable to display the correct format. I have tried everything this is how I need the code to display:

  Portfolio #00001, ASD = 42.50, DFAS = 45.00, CAC = 22.20, BDM = 52.50
  Portfolio #00002, ASD = 42.50, DFAS = 45.00, CAC = 22.20, BDM = 52.50
  Portfolio #00001, ASD = 43.35, DFAS = 45.90, CAC = 22.64, BDM = 53.55
  Portfolio #00002, ASD = 43.35, DFAS = 45.90, CAC = 22.64, BDM = 53.55
  Portfolio #00001, ASD = 41.18, DFAS = 43.61, CAC = 21.51, BDM = 50.87
  Portfolio #00002, ASD = 41.18, DFAS = 43.61, CAC = 21.51, BDM = 50.87
  Portfolio #00001, ASD = 43.65, DFAS = 46.22, CAC = 22.80, BDM = 53.92
  Portfolio #00002, ASD = 43.65, DFAS = 46.22, CAC = 22.80, BDM = 53.92

And this is how my code is displaying:

Portfolio #00001, ASD = 42.50, 
Portfolio #00001, DFAS = 45.00, 
Portfolio #00001, CAC = 22.20, 
Portfolio #00001, BDM = 52.50, 
Portfolio #00002, ASD = 42.50, 
Portfolio #00002, DFAS = 45.00, 
Portfolio #00002, CAC = 22.20, 
Portfolio #00002, BDM = 52.50, 

this is the code:

   public void display() {
    for (Map.Entry<String, Double> entry : priceMap.entrySet()) {
        System.out.printf("\nPortfolio #%s, " + "%s = " + "%.2f, ",
                ticker, entry.getKey(), entry.getValue());
    }
}    

Please help, why are they going to a new line after the second entry.

Upvotes: 0

Views: 90

Answers (2)

Buzz Moschetti
Buzz Moschetti

Reputation: 7578

Well, you've got a rogue \n in your printf. But I think the logic you seek is more like this.

public void display(String ticker) {
    System.out.printf("Portfolio #%s", ticker);
    for (Map.Entry<String, Double> entry : priceMap.entrySet()) {
        System.out.printf(", %s = " + "%.2f", entry.getKey(), entry.getValue());
    }
    System.out.println();   // finish up the line.
}

Upvotes: 1

musical_coder
musical_coder

Reputation: 3896

Your printf has only three parameters. You need to add a parameter for each value you want printed.

For example, to add the next column you expect, change it to:

System.out.printf("\nPortfolio #%s, " + "%s = " + "%.2f, DFAS = %.2f",
            ticker, entry.getKey(), entry.getValue(), getDFASValue());  // <-- You need to specify what the DFAS value is

Continue until you've filled in parameters for every item you want.

Upvotes: 0

Related Questions