1

I created a two-dimensional array that I want to fill with random digits within a range up to 10. However, the printed end-result ends up being all zeros. I cannot see what is wrong with my code, and I am certain everything is correct. I searched for similar issues here at Stack Overflow, but cannot find a problem that is similar to mine. My code is below:

int [][] array = new int [3][3];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++)
{   array[i][j] = ( (int) Math.random() * 10 );  
System.out.print(array[i][j] + " ");  } 
System.out.println(" ");     }
Anne Bailly
  • 391
  • 3
  • 9
  • 3
    *Casting* has higher precedence than multiplication making `(int) Math.random() * 10` be executed as it was written `((int) Math.random()) * 10` (see the problem here? `Math.random()` returns values in range `[0...1)` where `1` is excluded). You want `(int) (Math.random() * 10)` – Pshemo Oct 29 '19 at 20:19
  • @Pshemo, I actually tried doing exactly as you did, prior to posting on Stack Overflow, but it didn't work :( – Anne Bailly Oct 29 '19 at 20:24
  • 1
    @AnneBailly try the full code I posted below it worked for me. – Omarito Oct 29 '19 at 20:25
  • @AnneBailly "...but it didn't work" could you include code you tried? As Omarito shown in his answer this solution should work fine. – Pshemo Oct 29 '19 at 20:55
  • 1
    @Pshemo, actually...the code did indeed work.What I had tried was slightly different, so the code both you and Omarito provided does indeed work as it should :) – Anne Bailly Oct 29 '19 at 22:48

1 Answers1

2

The problem is simple. Its just your casting Math.random() to int and not the result of the multiplication.
Your original code have this line :

array[i][j] = ( (int) Math.random() * 10 ); 

which will cast Math.random() to int while Math.random() return double in the interval [0..1]. The result of the cast to int will be then 0.
What you should do instead is casting the multiplication of Math.random() with 10:

array[i][j] = ( (int) (Math.random() * 10) ); 

Here is the full working code :

public class RandomArray{
     public static void main(String []args){
        int [][] array = new int [3][3];
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++){   
                array[i][j] = ( (int) (Math.random() * 10) );  
                System.out.print(array[i][j] + " ");  
            } 
            System.out.println(" ");    
        }
     }
}
Omarito
  • 577
  • 6
  • 22