Meme Boi Meme Boi - 9 months ago 50
Java Question

Trying to make a fencing map using terrain representation

Right now im looking to make a fence with 1's and 0's to represent terrain. 1 will be the fences, and 0 will be the empty spaces. Here is my code

package assignment_2;

public class Fencing {

public static void main(String[] args) {

boolean b = true;
int i;
int j;
int[] [] map =

{0, 1, 1, 0},
{1, 2, 1, 1},
{1, 1, 4, 0},
{1, 1, 0, 0}
for (i = 0; i < 4; i++){
for (j = 0; j < 4; j++){
if (map[i][j] != 1 && map[i][j] != 0){
b = false;

if (b = false){
System.out.println("Map of the land owned:");
System.out.println("Map does not have the correct format");
System.out.println("--> A value of " + map[i][j] + " was found at " + i + "," + j);

System.out.println("Map of the land owned: ");
System.out.println("The map is valid");

What i'm trying to make the code do is to display if a map is valid or not. The map cannot be valid if it is made of anything other than 0's or 1's, but for some reason this code is making the map valid no matter what is in it, and is displaying the first error in the map instead of printing out the whole map. I'm trying to make the final result look like this:

Map of land owned


The map is not valid
A value of 2 was found at 1,1
A value of 4 was found at 2,2

Heres what the result looks like right now

Map of the land owned:
The map is valid

It seems to be ignoring the b boolean for some reason, does anyone know how to fix it?

Edit: The b problem has been fixed, this is what im getting now

Map of the land owned:
Map does not have the correct format
--> A value of 2 was found at 1,1

Answer Source

The reason it's ignoring the if (b = false) is because you are using an assignment operator, not a conditional operator. This will always evaluate to true, because you are assigning the value, thus making it true.

Change it to if (b == false) or as Balint pointed out (!b).