数组值未按预期工作

时间:2016-10-27 17:46:05

标签: java arrays eclipse math

我正在使用地形表示围栏,其中1是围栏,0是空格。这是代码:

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;

                }   
            }
        }       
    }
}

现在,此代码滚动数组值,如果有值不是1或0,则会将它们报告给用户。如果有错误,则显示所有错误的数字。它的问题是,在它拾取第一个错误后,它会对角滚动通过数组的其余部分并显示这些值而不是显示错误(数字不是1或0)。我认为这与代码的这一部分有关:

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

有谁知道要改变什么?

2 个答案:

答案 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; // 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"); }

答案 1 :(得分:-1)

 for (i = 0; i < 4; i++) {
            //set b to true for each Map
            b = true;
            for (j = 0; j < 4; j++) {
                if (map[i][j] != 1 && map[i][j] != 0) {
                        //found incorrect value, set b to false
                        b = false;
                        System.out.println("Map is Invalid :"+map[i][j]);
                    }  
                }
                //If b is true, then ONLY Map is VALID
                if(b) {
                    System.out.println("Map is VALID");
                }
            }