I am trying to make a matrix in Java
that is going to be filled with random values only in that positions that are empty. I am trying these code but it doesn't work.
I made two nested for
loops, one for the rows and one for the columns. And for every position, I ask if it's 0
(I'm not sure how to make a control on that) and if it does not generate a random coordinate and print it in the format (i,j). But it is always printing 0
.
public int[][] getRandomPosition(int matrixlength) {
int[][] grid = new int[matrixlength][matrixlength];
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if (grid[i][j] == 0) {
grid[i][j] = (int) Math.random();
System.out.print(grid[i][j]);
return grid;
}
}
}
return null;
}
Any idea of how I can resolve the problem at hand?
The reason as to why it's always printing zero is because of Math.random()
returns a number from 0.0
to 0.9
inclusive therefore once you cast the result returned from Math.random()
to an int
, it will always result in 0
.
Solution to your problem; you could either use the Random
class and utilize its nextInt
method or use the formula below:
grid[i][j] = (int)(Math.random() * (max - min) + min); // where min is the minimum value you want to generate and max is the max you want to generate (exclusive).
Though I'd recommend the former, and you'd first need to create a Random
object prior to the outer loop i.e
Random randomGen = new Random();
then within your, if
block, you can do:
grid[i][j] = randomGen.nextInt();
There's also another Random#nextInt
overload which enables you to specify the bounds of the random numbers being generated.