繁体   English   中英

是否缺少正确对齐我的 output 的值?

[英]Is there a value missing to correctly align my output?

我在我的 output 中获得了正确的信息,但希望它在直列中的数字方面看起来更有条理。

public class Main 
    {
      public static double classAvg(int [] list) 
      {
        int sum = 0;
        for (int x:list)
          sum+=x;
        return (double)sum/list.length;
      }
      public static void main(String[] args) 
          throws IOException 
      {
          Scanner f = new Scanner(new File("students.in"));
          int N = f.nextInt();

          String [] name = new String[N];
          int [] avg = new int[N];
          for (int x=0;x<N;x++)
          {
            f.nextLine();
            name[x]=f.nextLine();
            avg[x]=f.nextInt();
          }
          for (int x=0;x<N;x++)
              out.printf("%s\t%d\n",
                  name[x],avg[x]);
          out.printf("Class average = %.1f\n",
              classAvg(avg));
      }
    }

这是我得到的 output:

Tom Jones   100
Sally Field 95
Travis Farmer   75
Joe Dirt    70
Carmen SanDiego 98
Class average = 87.6

您可以使用 printf 格式来解决它,例如%-20s ,它是左对齐,宽度为 20 个字符。

out.printf("%-20s\t%d\n", name[x],avg[x]);

请参考DZONE中的 javadoc 或类似的示例
其他库/类,例如来自 apache commons lang 的 StrBuilder 也有很好的格式化功能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM