[英]Java: For loop print statement for two dimensional array
I'm trying to do a two dimensional for loop that with print this: 我正在尝试使用打印此的二维for循环:
7 5 3 1 7 5 3 1
2 4 6 8 2 4 6 8
Here is my array: 这是我的数组:
int [][] secondArray = {{7, 5, 3, 1}, {2, 4, 6, 8}};
The for loop below will only print it one number after the other. 下面的for循环将只打印一个数字。 Not all on one straight line. 并非全部都在一条直线上。 I have tried playing around with it. 我试过了。 Like making two print statements. 就像制作两个打印语句一样。 On for i and j. 对于i和j。 Or doing a "\\t". 或执行“ \\ t”。 I'm just learning arrays and this for loop was the closest example I got online. 我只是在学习数组,这个for循环是我上线后最接近的示例。
for(int i = 0; i < secondArray.length ; i++)
{
for(int j = 0; j < secondArray[i].length; j++)
{
System.out.println(secondArray[i][j]);
}
}
Edit: I guess I should put that I understand how for loops work. 编辑:我想我应该说我了解for循环如何工作。 It goes through each number and prints it. 它遍历每个数字并打印出来。 I guess my question is, how else would I do this? 我想我的问题是,我还能怎么做?
Use a foreach loop and print a line everytime you jump from one inner array to another: 每次从一个内部数组跳转到另一个内部数组时,请使用foreach循环并打印一行:
for(int[] a : secondArray) {
for(int b : a) {
System.out.print(b);
System.out.print(' ');
}
System.out.println();
}
Use System.out.print() instead of System.out.println() if you don't want to the next output to be from next line. 如果您不想下一个输出来自下一行,请使用System.out.print()而不是System.out.println()。
Code 码
for(int i = 0; i < secondArray.length ; i++) {
for(int j = 0; j < secondArray[i].length; j++) {
System.out.print(secondArray[i][j] + " ");
}
System.out.println();
}
this also works.. 这也可以..
int [][] secondArray = {{7, 5, 3, 1}, {2, 4, 6, 8}};
for (int i = 0; i < secondArray.length ; i++)
{
for(int j = 0; j < secondArray[i].length; j++)
{
System.out.print(secondArray[i][j]);
System.out.print(' ');
}
System.out.println();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.