javaarraystype-2-dimension

Random numbers with a 2d array


I'm working on an assignment for a class where I first need to declare integer array with 5 rows and 5 columns. Then initialize the array elements to random numbers between one and ten. The output is just a long list of 3 and nothing else. If you could point me in the right direction that would be very much appreciated.

I have to use this statement for random:

int r = (int)(Math.random()*(9-1+1))+1;

This is what I have so far and it's not working:

public static void main(String[] args) {
    // TODO Auto-generated method stub
int[][] table= new int [5][5];
int r = (int)(Math.random()*(9-1+1))+1;

for(int row = 0; row < table.length; row++){
for(int column = 0; column < table[row].length; column++){
    table[row][column]=r;
    System.out.println(table[row][column]);
}
}

}

}

Solution

  • Because you are calculating r before the loop,

    int r = (int)(Math.random()*(9-1+1))+1;
    

    all of the numbers in your table are goint to be the same. Move this inside of the loop as such:

    for(int row = 0; row < table.length; row++){
        for(int column = 0; column < table[row].length; column++){
            int r =(int)(Math.random()*(9-1+1))+1;
            table[row][column]=r;
            System.out.println(table[row][column]);
        }
    }
    

    PS.

    (int)(Math.random()*(9-1+1))+1;

    could probably be shortened to

    (int)(Math.random()*9)+1;