无法使平均值正确对齐

时间:2013-04-23 22:51:37

标签: java formatting

更多hw问题:D我需要对齐平均值。我试过,但是学生名字的长度不同,使用printf的程度有一定程度,但是对于名字比其他人更长,他们没有排队。我不知道怎么让他们排队

System.out.println("You Chose Student Average\n");
                int avg;

                while(inFile.hasNext())
                {
                    name = inFile.next();
                    test1 = inFile.nextInt();
                    test2 = inFile.nextInt();

                    avg = (test1 + test2)/2;

                    System.out.print(name);
                    System.out.printf("%14d\n", avg);
                }
                System.out.print("\n");

然后是平均值输出:

Robert            76
Joel            57
Alice            96
Jasmine            84
Larry            55
Elizabeth            82
Frank            70
Christine            28
Alex            26
Ariel            82
Luis            71
Nicole            64
Mitch            92
Randy            87
Tammy            87
Sarah            74
Samuel            73
Lauren            59
Deanna            98
Mathew            93
Justin            72
Beth            95
Rebecca            84
Paul            54
Lucy            45

做什么?

2 个答案:

答案 0 :(得分:0)

您可以使用字符串格式而不仅仅是整数。 http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax

但是,除非您有一个明确定义的最大名称长度,否则我认为您可以做的最好是检查最大名称长度,然后在所有其他名称中添加空格,直到它们匹配为止。

答案 1 :(得分:0)

尝试使用“\ t”。像:

System.out.println("Name: \t" + average);

修改

由于您正在使用printf,请尝试:

System.out.printf("%14d \t \n", avg);