[英]How can I print the results of 2 for loops on the same line
I am trying to get the code to run so that the output looks like this, 我试图让代码运行,以便输出看起来像这样,
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("[]");
}
}
I seem to be printing the []
on to the next line, but I can't seem to figure out how to put the []
on the line above. 我似乎将
[]
打印到下一行,但似乎无法弄清楚如何将[]
放在上一行。 I tried using printf(%d %d | %s%n)
, but that doesnt work too well from what i have tried and just creates more problems. 我尝试使用
printf(%d %d | %s%n)
,但是从我尝试过的方法来看效果不佳,只会造成更多问题。 Is there anyway to move the []
back a line? 反正有
[]
移回一行吗?
You can create the bucket string before the printf
statement and then print the string at once like 您可以在
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);
}
Since printf
prints a new line when you enter %n
, I suggest using something like this (replace %n
with a space, add println
after the loop): 由于在输入
%n
时printf
打印新行,因此我建议使用类似的东西(用空格替换%n
,在循环后添加println
):
for(int i = buckets.length - 1; i >= 0; i--) {
System.out.print("%2d-%3d | ", i * 10 + 1, i * 10 + 10);
for(int j = 0; j < buckets[i]; j++){
System.out.print("[]");
}
System.out.println("");
}
the println
statement will give you the newline in the place you want. println
语句将在所需位置为您提供换行符。
System.out.printf()
and System.out.println()
add a new line at the end. System.out.printf()
和System.out.println()
在末尾添加新行。 So just use System.out.print()
and at the end of a line use System.out.println()
因此,只需使用
System.out.print()
然后在一行的末尾使用System.out.println()
for(int i = buckets.length - 1; i >= 0; i--)// RELEVANT PARTS TO QUESTION
System.out.print("%2d-%3d |", i * 10 + 1, i * 10 + 10);
for(int j = 0; j < buckets[i]; j++){
System.out.print("[]");
}
System.out.println();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.