簡體   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