Reputation: 3
I am trying to create an array and have it filled with 0 or 1's randomly throughout the array. Below you will find the code. I am very new to java so any help would be greatly appreciated.
private static void randHouse() {
int rows = 4;
int columns = 5;
int i = 0;
int y = 0;
int [][] myList = {
{0,0,0,0,0},
{0,0,0,0,0},
{0,0,0,0,0},
{0,0,0,0,0}
};
System.out.println(Arrays.deepToString(myList)); // just prints the array
for (i : rows); {
for (y : columns);{
myList[i][y] = (int)random() * 10;
}
}
}
I am currently getting the error : java: bad initializer for for-loop
Upvotes: 0
Views: 66
Reputation: 40062
It is easiest (imo) to use streams.
int r = 4;
int c = 5;
int[][] result = randHouse(r,c);
for (int[] row : result) {
System.out.println(Arrays.toString(row));
}
Prints something like
[1, 1, 0, 1, 1]
[0, 1, 0, 0, 1]
[1, 0, 1, 1, 1]
[1, 0, 1, 0, 0]
IntStream
iterates over the rowsprivate static int[][] randHouse(int r, int c) {
Random rand = new Random();
return IntStream.range(0, r)
.mapToObj(i -> rand.ints(c, 0, 2).toArray())
.toArray(int[][]::new);
}
Note: In your original problem, (int)Math.random()*10
will first convert the random value to 0 and then multiply by 10. So all you get are zeros. If you did the following (int)(Math.random()*10)
you would get a value between 0
and 9
inclusive. Instead of 10
, you should use 2
.
Upvotes: 1
Reputation: 232
for (int i = 0; i < rows.length; i++) {
for (int j = 0; j < columns.length; j++) {
myList[i][j] = (int)random() * 10;
}
}
Upvotes: 1