gpt4 book ai didi

java - 是否缺少正确对齐输出的值?

转载 作者:行者123 更新时间:2023-12-01 16:38:09 24 4
gpt4 key购买 nike

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

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));
}
}

这是我得到的输出:

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 或类似示例
其他图书馆/类(class),例如来自 apache commons lang 的 StrBuilder 也有很好的格式化功能。

关于java - 是否缺少正确对齐输出的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61916173/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com