• 0

[Java] 2D Boolean Array and Randomness


Question

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 Diller
Link to comment
Share on other sites

4 answers to this question

Recommended Posts

  • 0

if (board[x][y] == true){
  board[x][y] = true;
}
 else { // do stuff

Just a quick comment or two on this code:

if (expression == true) is the same as if(expression) but longer!

if (var) {var = true;} is redundant, var is set to tue only if it's atready set to true!

So your code would be better written

if (! board[x][y]) {
   // do stuff

Link to comment
Share on other sites

  • 0
if (board[x][y] == true){
  board[x][y] = true;
}
 else { // do stuff

Just a quick comment or two on this code:

if (expression == true) is the same as if(expression) but longer!

if (var) {var = true;} is redundant, var is set to tue only if it's atready set to true!

So your code would be better written

if (! board[x][y]) {
   // do stuff

Yeah, I realized this afterwards and it's something I'm going to change later today - helps prevent typos with = instead of == so it's got another benefit too!
You are not resetting Y to 0 when you finish the inside loop
Correct, that code did not. I have fixed it since so it's all good.
Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.