I am trying to write a nested for loop that will print out the values of the following code in a specific order:
我正在尝试编写一个嵌套的for循环,它将按特定顺序打印出以下代码的值:
public static void main(String[] args) {
int[][] array2d = new int[3][5];
for (int i = 0; i < array2d.length; i++) {
for (int j = 0; j < array2d[0].length; j++) {
array2d[i][j] = (i * array2d[0].length) + j + 1;
}
}
for (int x = 0; x <= 4; x++) {
for (int y = 0; y <= 2; y++) {
System.out.println(array2d[y][x]);
}
}
}
}
The current array prints the way I want it, but each printout on a separate line.
当前数组以我想要的方式打印,但每个打印输出在单独的行上。
I want the output (on a single line) to be this:
我希望输出(在一行上)是这样的:
1 6 11 2 7 12 3 8 13 4 9 14 5 10 15
Thanks for the help.
谢谢您的帮助。
4 个解决方案
#1
1
You can use System.out.print
instead:
您可以使用System.out.print:
System.out.print(array2d[y][x] + " ");
#2
1
Replace println
with print
and it should work
用打印替换println它应该工作
#3
1
String s = "";
for (int i = 0; i < array2d.length; i++) {
for (int j = 0; j < array2d[i].length; j++) {
s += array2d[i][j] + " ";
}
}
System.out.println(s);
#4
0
public static void main(String[] args) {
int[][] array2d = new int[3][5];
for (int i = 0; i < array2d.length; i++) {
for (int j = 0; j < array2d[0].length; j++) {
array2d[i][j] = (i * array2d[0].length) + j + 1;
}
}
StringBuilder builder = new StringBuilder();
for (int x = 0; x <= 4; x++) {
for (int y = 0; y <= 2; y++) {
builder.append(array2d[y][x]);
if(!(x == 4 && y == 2)){
builder.append(" ");
}
}
}
System.out.println(builder.toString());
}
You basically had it right, except for changing the println
to be print
and formatting the string how you want. I changed it a little to show how the StringBuilder
works. Whenever possible I use a StringBuilder
because it is more convenient.
除了将println更改为要打印并根据需要格式化字符串之外,您基本上都是正确的。我稍微改了一下,以显示StringBuilder的工作原理。我尽可能使用StringBuilder,因为它更方便。
#1
1
You can use System.out.print
instead:
您可以使用System.out.print:
System.out.print(array2d[y][x] + " ");
#2
1
Replace println
with print
and it should work
用打印替换println它应该工作
#3
1
String s = "";
for (int i = 0; i < array2d.length; i++) {
for (int j = 0; j < array2d[i].length; j++) {
s += array2d[i][j] + " ";
}
}
System.out.println(s);
#4
0
public static void main(String[] args) {
int[][] array2d = new int[3][5];
for (int i = 0; i < array2d.length; i++) {
for (int j = 0; j < array2d[0].length; j++) {
array2d[i][j] = (i * array2d[0].length) + j + 1;
}
}
StringBuilder builder = new StringBuilder();
for (int x = 0; x <= 4; x++) {
for (int y = 0; y <= 2; y++) {
builder.append(array2d[y][x]);
if(!(x == 4 && y == 2)){
builder.append(" ");
}
}
}
System.out.println(builder.toString());
}
You basically had it right, except for changing the println
to be print
and formatting the string how you want. I changed it a little to show how the StringBuilder
works. Whenever possible I use a StringBuilder
because it is more convenient.
除了将println更改为要打印并根据需要格式化字符串之外,您基本上都是正确的。我稍微改了一下,以显示StringBuilder的工作原理。我尽可能使用StringBuilder,因为它更方便。