简体   繁体   English

如何使用随机数打印二维数组

[英]How to print a 2D array with random numbers

I am trying to write a program that prints a 2d array with random numbers ranging from 100-10000 and prints out the max number in the array,average,and min. 我正在尝试编写一个程序,该程序将打印2d数组,其随机数范围为100-10000,并打印出数组中的最大数,平均值和最小值。 The program will ask the user for the number of rows and column and print random numbers in that array. 该程序将询问用户行数和列数,并在该数组中打印随机数。

Here is my code: 这是我的代码:

Random rand = new Random();

int randomnumber = rand.nextInt(9901) + 100;

Scanner console = new Scanner(System.in);

System.out.println("Enter row");
int n = console.nextInt();

System.out.println("Enter column");
int y = console.nextInt();

int[][] array = new int[n][y];
array[n][y] = randomnumber;

int k;
for (int i = 0; i <= array.length; i++) {
    for (k = 0; k <= array[i].length; k++) {
        System.out.print(array[i][k]);
    }
}

If you want to fill the array with random values, you need to generate random values in a loop, and then write them to the array in that loop. 如果要用随机值填充数组,则需要在循环中生成随机值,然后在该循​​环中将它们写入数组。 So far you are only generating one value (and putting it in an invalid location). 到目前为止,您仅生成一个值(并将其放在无效位置)。

Additionally, since arrays are 0-based, your loops should be for(i=0; i<arr.length; i++); 另外,由于数组是基于0的,因此循环应为for(i=0; i<arr.length; i++); , not <= . ,不是<=

Here's some code: 这是一些代码:

// don't declare k here
for(int i=0;i<array.length;i++){

 for(int k=0;k<array[i].length;k++){
      array[i][k]=rand.nextInt(9901)+100;
      System.out.print(array[i][k]);


 }
 System.out.println(); // separate rows
}

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

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