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
I would change this line:
array[i][j] = (int) (Math.round(Math.random() * (size + 1)) - size / 2);
to:
array[i][j] = ThreadLocalRandom.current().nextInt( -size, size + 1);
to generate a random int value in a specific range, here [-size, size]
I suggest using ThreadLocalRandom
which provides a handy method: nextInt(int origin, int bound)
. Which can then be used in your loop like this:
int[][] array = new int[size][size];
ThreadLocalRandom r = ThreadLocalRandom.current();
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
array[i][j] = r.nextInt(-size, size + 1);
}
}
The first argument origin
defines from where the numbers should start and the second argument bound
limits the generated numbers to a given value exclusivly.
because round of 1.5 is 2, so in other words supposing random()=1 and size=1 then you have 1*(1+1))-1/2 so (2-1)/2
round(1.5)=2
instead use .floor(x) method or not use round, as you have casting to int, this should also work (as @Lino pointed out).
Summarizing the result of rounding for 1.5 is 2, use floor so you will have 1.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.