简体   繁体   English

用随机整数填充二维数组

[英]FIlling a 2D array with random integers java

I am trying to create an nxn array full of random integers between 1 and 10. When I try to print it out, I am getting an odd number of integers not filling an array, and never up to the correct number of integers (for instance, a supposed 5x5 array is returning 17 integers). 我正在尝试创建一个充满1到10之间的随机整数的nxn数组。当我尝试将其打印出来时,我得到的是奇数个整数未填充数组,并且从未达到正确的整数数(例如,假设5x5数组返回17个整数)。 Code snippet follows, assume all variable are declared correctly unless contained in here and java.util.Random is imported. 代码段如下,假定所有变量都正确声明,除非此处包含且导入了java.util.Random。

if (choice==1){
     Random rand = new Random();
     System.out.println("Please input a power n for (nxn array) between 1-6");
     int power = kb.nextInt();
     int[][] randMatrix = new int[power-1][power-1];
     if (power < 1 || power > 6){
        System.out.println("Invalid power");
     }else{
        for (i=0; i<randMatrix.length; i++){
           for (j=0; j<randMatrix.length; j++){
              randMatrix[i][j] = rand.nextInt(9);
           }
        }for (i=0; i<randMatrix.length; i++){
           for (j=0; j<randMatrix.length; j++){
              System.out.println(randMatrix[i][j]);
           }
        }
     }
  }

It doesn't print 17 integers, it prints 16. This is because 16 is 4 * 4 and you should have done 它不打印17个整数,而是打印16个。这是因为16是4 * 4,您应该这样做

new int[power][power]

rather than 而不是

new int[power-1][power-1]

The comments are also correct that it should be 评论也应该是正确的

for (j = 0; j < randMatrix[i].length; j++)

but this does not explain your problem, as the array is square. 但这不能解释您的问题,因为数组是正方形的。

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

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