如何自动填充数字的二维数组 [英] how to automatically populate a 2d array with numbers

查看:149
本文介绍了如何自动填充数字的二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好我试图自动填充基于用户输入一个二维数组。
用户将进入1号,这个号码将设置二维数组的大小。然后我想打印出数组的数字。
例如,如果用户输入的号码4。 2D阵列将4行×4 colums,并应包含数1〜16,并打印出如下

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

但我努力想将做到这一点正确的说法。
就目前我的code刚刚打印出包含二维数组*。

有没有人任何想法如何,我可以打印出来的数字,我真的卡住。
我的code如下:

 公共静态无效的主要(字符串ARGS []){    扫描仪输入=新的扫描仪(System.in);
    的System.out.println(进入房间的长度);    INT NUM1 = input.nextInt();
    INT NUM2 NUM1 =;
    INT长度= NUM​​1 * NUM2;
    的System.out.println(房间+ NUM1 +X+ NUM2 +=+长);    INT [] [] =电网新INT [NUM1] [NUM2];    对于(INT行= 0;&行LT; grid.length;排++){
        对于(INT COL = 0;&山坳下,电网[行]。长度;西++){
            System.out.print(*);
        }
        的System.out.println();
    }
}


解决方案

读取n值

  INT [] [] =改编新的INT [n] [N];
INT增量= 1;
的for(int i = 0; I< N;我++)
对于(INT J = 0; J< N; J ++)
{
改编[I] [J] = INC;
INC ++;
}

Hi i am trying to auto populate a 2d array based on user input. The user will enter 1 number, this number will set the size of the 2d array. i then want to print out the numbers of the array. for example , if the user enters the number 4 . the 2d array will be 4 rows by 4 colums, and should contain the number 1 to 16, and print out as follows.

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

But i am struggling to think of the right statement that will do this. for the moment my code just prints out a 2d array containing *.

Has anyone any ideas how i could print out the numbers , i'm really stuck. my code follows:

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

解决方案

Read n value,

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

这篇关于如何自动填充数字的二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆