gpt4 book ai didi

java - 如何在同一行打印 2 个 for 循环的结果

转载 作者:搜寻专家 更新时间:2023-11-01 08:29:25 26 4
gpt4 key购买 nike

我正在尝试让代码运行,以便输出看起来像这样,

91-100 | [][][][][][][][][]81- 90 | [][][][][]71- 80 | [][][][][][][][][][]61- 70 | [][]51- 60 | []41- 50 | [][]31- 40 |21- 30 |11- 20 | 1- 10 | [][][]

But currently, my output is looking like this,

91-100 |[][][][][][][][][]81- 90 |[][][][][]71- 80 |[][][][][][][][][][]61- 70 |[][]51- 60 |[]41- 50 |[][]31- 40 |21- 30 |11- 20 | 1- 10 |[][][]

Here is my code:

 int[] buckets = new int[10];
while(scan.hasNextLine()){
String line = scan.nextLine();
String[] array = line.split(separator);
String grade = array[1];
int number = Integer.parseInt(grade.trim());
buckets[(number - 1)/10]++;
}
for(int i = buckets.length - 1; i >= 0; i--)// RELEVANT PARTS TO QUESTION
System.out.printf("%2d-%3d |%n", i * 10 + 1, i * 10 + 10);
for(int j = 0; j < buckets[i]; j++){
System.out.print("[]");
}
}

我似乎将 [] 打印到下一行,但我似乎无法弄清楚如何将 [] 放在上面的行.我尝试使用 printf(%d %d | %s%n),但从我的尝试来看效果不是很好,只会产生更多问题。无论如何要将 [] 移回一行?

最佳答案

您可以在 printf 语句之前创建存储桶字符串,然后像这样立即打印该字符串

 for (int i = buckets.length - 1; i >= 0; i--) {        
String bucketsString = "";

for(int j = 0; j < buckets[i]; j++)
bucketsString = bucketsString.concat("[]");

System.out.printf("%2d-%3d | %s %n", i * 10 + 1, i * 10 + 10, bucketsString);
}

关于java - 如何在同一行打印 2 个 for 循环的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42012593/

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