'I do not understand this part. Can anyone explain how this loop and math.random*2 is working [closed]

help me to understand this code

public class Exercise12 {

public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    System.out.print("Input a number: ");
    int n = in.nextInt();
    printMatrix(n);
}

public static void printMatrix(int n) {

    for(int i = 0; i < n; i++) {
        for(int j = 0; j < n; j++) {
            System.out.printin((int)(Math.random() * 2) + " ");
        }
        System.out.println();
    }
}

}



Solution 1:[1]

Math.random() returns a number between 0.0 (inclusive) and 1.0 (exclusive).

Therefore (Math.random() * 2) is a number between 0.0 (inclusive) and 2.0 (exclusive).

Therefore (int)(Math.random() * 2) is either 0 or 1:

  • If (Math.random() * 2) == 0.xxxx, casting it to int results in 0
  • If (Math.random() * 2) == 1.xxxx, casting it to int results in 1

Hence this code prints a matrix of n * n 0 or 1 elements.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eran