gpt4 book ai didi

java - 数组值未按预期工作

转载 作者:行者123 更新时间:2023-12-01 06:08:20 26 4
gpt4 key购买 nike

我正在使用地形表示来制作栅栏,其中 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++;

有人知道要改变什么吗?

最佳答案

您可以将程序修改为:

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

关于java - 数组值未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40291105/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com