How do I find the product of all the elements of a two-dimensional array?

In the product, it always outputs 0. Everything is fine with a one-dimensional array, but when working with a two-dimensional array, 0 is output.

public class Test {
    public static void main(String[] args) {
        int[][] a = new int[3][3];
        for (int i = 0; i < 3; i++)
            for (int j = 0; j < 3; j++)
                a[i][j] = (int) (Math.random()) * 10;
        int r = 1;
        for (int i = 0; i < 3; i++)
            for (int j = 0; j < 3; j++)
                r = r * a[i][j];
        System.out.println(r);
    }
}
Author: Rascheras, 2020-11-28

3 answers

First, move the bracket for 10

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

And secondly, what will the product be if there is at least one 0 in the table? Add another unit:

a[i][j] = (int)(Math.random() * 10) + 1;
 0
Author: Эникейщик, 2020-11-28 20:58:19
a[i][j] = (int)(Math.random() * 10) + 1;
 1
Author: Igor, 2020-11-28 20:57:15

Method Math.random() returns a fractional number double in the range greater than or equal to 0.0 and less 1.0, which when cast to int becomes 0, i.e. you have an empty array! An integer pseudo-random number in a given interval can be obtained using the method Random.nextInt(n):

Random random = new Random();
random.nextInt(10); // [0, 9]

Your code might look like this:

int[][] a = new int[3][3];
Random random = new Random();
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
        a[i][j] = 1 + random.nextInt(10); // [1, 10]
    }
}
int r = 1;
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
        r = r * a[i][j];
    }
}
System.out.println(Arrays.deepToString(a));
// [[4, 2, 8], [8, 7, 8], [1, 9, 10]]
System.out.println(r);
// 2580480
 1
Author: , 2020-11-28 21:42:48