Below is some simple code I am working on to essentially randomly create true or false values in a 2D boolean array. Presently I am using the following code, and it keeps on making the first row (board[0][x]) variable (can be either) and all other values false, which makes me wonder:
1 - Are elements in a boolean array automatically assigned a value?
2 - Will my embedded 'while' loops fail after the first row?
3 - Is there an easier way other than making a random number and testing its value against the mid-ground?
Random numgen = new Random(); //Make a random number
int x=0;
int y=0;
boolean board[][];
board = new boolean[3][3];
while(x<board.length){
while(y<board[0].length){
//Checks to see if the element is already true. If it is, leave it be.
if (board[x][y] == true){
board[x][y] = true;
}
//Randomly assign elements to be true or false
else {
int prob = numgen.nextInt(2) + 1;
if (prob==1){
board[x][y] = true; //Element is true
}
else board[x][y]=false; //Element is false
}
y++;
}
x++;
}
Any help would be appreciated.
Update: Got it somewhat fixed, but it still seems like it's only running through the outside loop once then just ending.
Got it, just had to use a for loop instead on the inside.. Bingo!
Question
Dave Diller
Below is some simple code I am working on to essentially randomly create true or false values in a 2D boolean array. Presently I am using the following code, and it keeps on making the first row (board[0][x]) variable (can be either) and all other values false, which makes me wonder:
1 - Are elements in a boolean array automatically assigned a value?
2 - Will my embedded 'while' loops fail after the first row?
3 - Is there an easier way other than making a random number and testing its value against the mid-ground?
Random numgen = new Random(); //Make a random number int x=0; int y=0; boolean board[][]; board = new boolean[3][3]; while(x<board.length){ while(y<board[0].length){ //Checks to see if the element is already true. If it is, leave it be. if (board[x][y] == true){ board[x][y] = true; } //Randomly assign elements to be true or false else { int prob = numgen.nextInt(2) + 1; if (prob==1){ board[x][y] = true; //Element is true } else board[x][y]=false; //Element is false } y++; } x++; }Any help would be appreciated.
Update: Got it somewhat fixed, but it still seems like it's only running through the outside loop once then just ending.
Got it, just had to use a for loop instead on the inside.. Bingo!
Edited by Dave DillerLink to comment
Share on other sites
4 answers to this question
Recommended Posts