繁体   English   中英

嵌套循环和 2D arrays - Output 不形成表格

[英]Nested Loops and 2D arrays - Output doesn't form a Table

我正在尝试创建一个允许我使用二维数组和嵌套for循环创建网格的程序。

问题是当我运行程序时,数字没有形成表格,而是打印在垂直列中。

我首先设置了包含 3 行的数组,每行具有任意值。 然后我使用嵌套的 for 循环,其中第一个循环用于创建循环将运行的行,第二个循环用于创建列。

package nestedLoops;

public class Trial_1 {

    public static void main(String[] args) {
        
        int[][] grid = {
                {1, 2, 3, 4, 5},
                {1, 2, 3, 4},
                {1, 2, 3, 4, 5}
                
        };

        for(int i=0; i<grid.length; i++ ) {
            for(int j=0; j<grid[i].length; j++) {
                System.out.println(grid[i][j]);
            }
        }
    }

}

然而,当我运行上面的代码时,我得到了这个 output:

1
2
3
4
5
1
2
3
4
1
2
3
4
5

我认为你需要这样的东西:

    for (int[] ints : grid) {
        for (int anInt : ints) {
            System.out.print(anInt);
        }
        System.out.println();
    }

在第二个循环中,您需要打印“anInt”并换行,您需要在循环之间添加换行符。

打印每一行后,您必须将 output 推进到

为此,您需要一个System.out.println(); 嵌套循环后的语句。

在嵌套循环中,您需要使用System.out.print(); (不是println )用于打印每一行的数字。 而且你还需要在行内的数字之间添加一个分隔符(空格、制表符等),否则它们会像12345那样混乱。

int[][] grid = {{1, 2, 3}, {11, 22, 33}};
    for (int i = 0; i < grid.length; i++) {
        for (int j = 0; j < grid[i].length; j++) {
            System.out.print(grid[i][j] + "\t");
        }
        System.out.println();
    }

Output

1   2   3   
11  22  33

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM