Meme Boi Meme Boi - 1 month ago 13
Java Question

Array value not working as intended

I'm making a fence using terrain representation where 1's are fences and 0's are empty spaces. Here is the 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, 1, 4},
{1, 3, 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 does not have the correct format");
while (i < 4 && j < 4){
System.out.println("--> A value of " + map[i][j] + " was found at " + i + "," + j);
i++;
j++;

}
}
}
else{
System.out.println("The map is valid");
return;

}
}
}
}
}


Right now this code scrolls through the array values, and if there are values that are not 1's or 0's then it reports them back to the user. If there are errors it displays all incorrect numbers. The problem with it is that after it picks up the first error, it scrolls diagonally through the rest of the array and shows those values instead of showing the errors (The numbers that aren't 1's or 0's). I think it has something to do with this part of the code:

while (i < 4 && j < 4){
System.out.println("--> A value of " + map[i][j] + " was found at " + i + "," + j);
i++;
j++;


Does anyone know what to change about it?

Answer

You can modify the program as :

    for (i = 0; i < 4; i++){
        for (j = 0; j < 4; j++){
            if (map[i][j] != 1 && map[i][j] != 0){
               b = false; // greedy approach can break or return here as well
                        System.out.println("--> A value of " + map[i][j] + " was found at " + i + "," + j);

                        }
                    }
               if (b == false){
                    System.out.println("Map does not have the correct format"); }
                else{
                System.out.println("The map is valid"); }