如何自动填充一个二维数组的数字

5

您好,我正在尝试根据用户输入自动填充二维数组。 用户将输入一个数字,此数字将设置二维数组的大小。然后,我想打印出数组中的数字。 例如,如果用户输入数字4,则二维数组将为4行4列,并应包含数字1到16,并按以下方式打印。

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

但我很难想出正确的语句来完成此任务。目前我的代码只能打印一个包含*的二维数组。

有人有什么想法可以打印数字吗?我真的陷入了困境。 以下是我的代码:

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();
    }
}

你是在问如何将正确的数字放入数组 grid 吗? - Ankit
4个回答

4

读取 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++;
    

感谢大家的评论,它们都很有帮助。我已经按照自己的想法让它正常工作了。 - derek

2

首先,您需要用数字填充数组。您可以使用双重循环和一个计数器变量,每次内部循环后将其递增。

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

之后,您可以使用双重循环再次输出数组。

0

我不确定我是否理解你的意思。

你的代码打印*有问题吗?

如果是的话,原因是这样的:

System.out.print("*");

应该是

System.out.print(grid[row]);  

0
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++;
        }
    }
}

这段代码应该按照你想要的方式打印出数字。

1
循环内的 if 判断应该使用 arraySize - 1 而不是 3 - Baz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接