int[] numbers = new int[100];
for (int i = 0; i < numbers.length; i++) {
if (i % 10 == 0 && i > 0) {
System.out.println();
}
System.out.print(numbers[i] + " ");
}
This prints a newline before printing numbers[i]
where i % 10 == 0
and i > 0
. %
is the mod operator; it returns the remainder if i / 10
. So i % 10 == 0
when i = 0, 10, 20, ...
.
As for your original code, you can make it work with a little modification as follows:
int count = 0;
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
count++;
if (count == 10) {
System.out.println();
count = 0;
}
}
Basically, count
is how many numbers you've printed in this line. Once it reaches 10, you print the newline, and then reset it back to 0, because you're starting a new line, and for that line, you haven't printed any numbers (yet).
Note that in above two solutions, an extra space is printed at the end of each line. Here's a more flexible implementation that only uses separators (horizontal and vertical) when necessary. It's only slightly more complicated.
static void print(int[] arr, int W, String hSep, String vSep) {
for (int i = 0; i < arr.length; i++) {
String sep =
(i % W != 0) ? hSep :
(i > 0) ? vSep :
"";
System.out.print(sep + arr[i]);
}
System.out.println(vSep);
}
If you call this say, as print(new int[25], 5, ",", ".
");
, then it will print 25 zeroes, 5 on each line. There's a period (.
) at the end of each line, and a comma (,
) between zeroes on a line.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…