java格式化程序输出不正确

时间:2015-03-24 18:08:20

标签: java string io formatting

try {
                FileWriter writer = new FileWriter("metrics.csv");
                Formatter fmt = new Formatter();
                fmt.format(
                        "%10s%10s%10s%10s%10s%10s%10s%10s%10s%10s%10s%3s", "",
                        "ANA", "NOM", "NOA", "ITC", "ETC", "CAC", "DIT",
                        "CLD", "NOC", "NOD", ",\n");
                for(int i = 0;i< class_list.getModel().getSize(); i++){
                    fmt.format(
                            "%10s%10s%10s%10s%10s%10s%10s%10s%10s%10s%10s%3s", declaration.getClassesName().get(i),
                            declaration.getANA(i), declaration.getNOM(i), declaration.getNOA(i), declaration.getITC(i), declaration.getETC(i), declaration.getCAC(i), declaration.getDIT(i),
                            declaration.getCLD(i), declaration.getNOC(i), declaration.getNOD(i), ",\n");
                }
                writer.append(fmt.toString());
                writer.flush();
                writer.close();
                System.out.println("done");
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }

所有get函数都返回一个长度小于10的字符串。 我得到的输出是:

             ANA       NOM       NOA       ITC       ETC       CAC       DIT       CLD       NOC       NOD ,
Equipe     0.33
     3         1         1         1         3         0         0         0         0 , 
Participant      0.0
     1         1         0         0         0         0         1         2         2 ,
Joueur     0.33
     3         3         0         1         1         1         0         0         0 , 
Entraineur      0.0
     1         2         0         0         1         1         0         0         0 ,
Stade      2.0
     1         2         1         0         1         0         0         0         0 ,

如您所见,该列未对齐。任何人都知道我的代码中的问题在哪里? 感谢。


编辑1: 这是我的getANA功能。

 public String getANA(){
    if (operations.size()==0) return "0";
    int arg_sum = 0;
    for(Operation o : operations){
        arg_sum+=o.getArgumentNumber();
    }
    return String.format("%.2g%n", (double)arg_sum/operations.size());
}

1 个答案:

答案 0 :(得分:2)

尝试在%n方法中取出getANA()

return String.format("%.2g", (double)arg_sum/operations.size());