簡體   English   中英

如何使用數字自動填充二維數組

[英]how to automatically populate a 2d array with numbers

嗨,我想嘗試根據用戶輸入自動填充二維數組。 用戶將輸入1個數字,此數字將設置2d數組的大小。 然后我想打印出數組的數字。 例如,如果用戶輸入數字4。 2d數組將是4行乘4列,並且應包含數字1到16,並打印如下。

1-2-3-4
5-6-7-8
9-10-11-12
13-14-15-16

但我正在努力思考能夠做到這一點的正確陳述。 目前我的代碼只打印出一個包含*的2d數組。

誰有任何想法如何打印出數字,我真的卡住了。 我的代碼如下:

public static void main(String args[]){

    Scanner input = new Scanner(System.in);
    System.out.println("Enter room length");

    int num1 = input.nextInt();
    int num2 = num1;
    int length = num1 * num2;
    System.out.println("room "+num1+"x"+num2+"="+length);

    int[][] grid = new int[num1][num2];

    for(int row=0;row<grid.length;row++){   
        for(int col=0;col<grid[row].length;col++){
            System.out.print("*");  
        }
        System.out.println();
    }
}

讀n值,

int[][] arr = new int[n][n];
int inc=1;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{
arr[i][j]=inc;
inc++;
}

好吧,首先你必須用數字填充數組。 你可以使用double for循環和一個計數器變量,它在內部for循環的每個循環之后遞增。

int counter = 1;
for(int x = 0; x < num1; x++)
{
    for(int y = 0; y < num2; y++)
    {
        grid[x][y] = counter++;
    }
}

之后,您可以使用double for循環再次輸出數組。

我不確定我是否理解你。 你有代碼打印問題*?

如果是,那么原因就是這個

System.out.print("*");

應該

System.out.print(grid[row]);  
public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    System.out.println("Enter room length");
    int arraySize = input.nextInt();
    System.out.println("Length: " + (arraySize*arraySize));

    int[][] array = new int[arraySize][arraySize];
    int count = 1;

    for (int i=0;i<arraySize;i++) {
        for (int j=0;j<arraySize;j++) {
            array[i][j] = count;
            if (j != (arraySize-1)) 
                System.out.print(count + "-");
            else
                System.out.println(count);
            count++;
        }
    }
}

此代碼應打印出您想要的數字。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM