lundi 11 février 2019

Filling an array with random numbers from the range [-n, n] using Math.random

I have a function in which I enter the size of the multidimensional array n. Next, I fill this array with random numbers in the range [-n, n], using Math.random ():

private int[][] enterMatrixSize() {
    System.out.print("enter matrix size (n): ");
    String input;
    while (!(input = in.next()).matches("\\p{Digit}+")) {
        System.out.print("Please enter a positive Integer: ");
    }
    int size = Integer.parseInt(input);
    int[][] array = new int[size][size];
    for (int i = 0; i < array.length; i++) {
        for (int j = 0; j < array[i].length; j++) {
            array[i][j] = (int) (Math.round(Math.random() * (size + 1)) - size / 2);
        }
    }
    for (int i = 0; i < array.length; i++, System.out.println()) {
        for (int j = 0; j < array[i].length; j++) {
            System.out.print(array[i][j]+" ");
        }
    }
    return array;
}

But it displays some incorrect values. For example, when I enter n equal to 1 - displays the numbers 0, 1 and 2. Which is strange. Since should output -1, 0, 1




Aucun commentaire:

Enregistrer un commentaire