-1

I am trying to assign numbers randomly. I understand that Math.random() only goes between 0 and 1, and tried to multiply it by 10, and it still does not show any random numbers:

 0 0 0 0 0
 0 0 0 0 0
 0 0 0 0 0
 0 0 0 0 0
 0 0 0 0 0

the code:

public static void main(String[] args) {

    int[][] mdArray = new int[5][5];

    for(int i = 0; i<mdArray.length; i++){
        for(int j = 0; j<mdArray[i].length; j++) {
            mdArray[i][j] = (int)Math.random()*10;
            System.out.print(mdArray[i][j] + " ");
        }
        System.out.println("");
    }
}
jrook
  • 3,459
  • 1
  • 16
  • 33
VerzChan
  • 53
  • 6

1 Answers1

0

This happens because your cast is wrong. The cast applies only to Math.random() with is less than 1, so it is always casted to 0 and 0*x = 0.

Instead of (int)Math.random()*10 you have to write (int) (Math.random() * 10).

Alex R
  • 3,139
  • 1
  • 18
  • 28