无法在Java中显示正确的格式

时间:2013-10-05 22:07:15

标签: java formatting

我无法显示正确的格式。我已经尝试了所有这些我需要显示的代码:

  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

这就是我的代码显示方式:

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, 

这是代码:

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

请帮忙,为什么他们会在第二次参赛后进入新的一行。

2 个答案:

答案 0 :(得分:1)

嗯,你\n中有一个流氓printf。但我认为你寻求的逻辑更像是这样。

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.
}

答案 1 :(得分:0)

您的printf只有三个参数。您需要为要打印的每个值添加参数。

例如,要添加您期望的下一列,请将其更改为:

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

继续,直到您填写了所需的每个项目的参数。