【发布时间】:2017-05-09 18:13:29
【问题描述】:
我很难弄清楚为什么方法工作不正确。
我的方法addtoHash() 总是返回true,并且由于某种原因它也只在返回true 之前查看第一个值。
对不起,如果这有点令人困惑,我的代码应该更好地解释它!
原来我的代码是这样的,它确实有效:
public void addtoHash(Set reserve, int value)
{
if(value > 0 && value < 10)
{
reserve.add(value)
}
}
public boolean squareCheck(int[][][] board, int index)
{
Set<Integer> reserve = new HashSet<>();
for(int r = 0; r < board[0].length; r++)
{
for(int c = 0; c < board[0].length; c++)
{
addtoHash(reserve,board[index][r][c]);
if(r == 2 && c == 2 && reserve.size() < 9)
{
System.out.println("Error in grid " + index);
return false;
}
}
}
return true;
}
因为我想让它更有用,所以我将 addtoHash() 改为返回布尔值:
public boolean addtoHash(Set reserve, int value)
{
if(value > 0 && value < 10)
{
return reserve.add(value) == true;
}
return false;
}
public boolean squareCheck(int[][][] board, int index)
{
Set<Integer> reserve = new HashSet<>();
for(int r = 0; r < board[0].length; r++)
{
for(int c = 0; c < board[0].length; c++)
{
if(!addtoHash(reserve,board[index][r][c]))
System.out.println("Error at " + index+r+c);
return false;
}
}
return true;
}
检查这是否有效:
int[][][] solved = {{{5,3,2},{6,7,2},{1,9,8}}, //My new code doesn't find the duplicate and return false here, despite my previous code having done so!
{{6,7,8},{1,9,5},{3,4,2}},
{{9,1,2},{3,4,8},{5,6,7}},
{{8,5,9},{4,2,6},{7,1,3}},
{{7,6,1},{8,5,3},{9,2,4}},
{{4,2,3},{7,9,1},{8,5,6}},
{{9,6,1},{2,8,7},{3,4,5}},
{{5,3,7},{4,1,9},{2,8,6}},
{{2,8,4},{6,3,5},{1,7,9}}};
validCheck checker = new validCheck();
checker.squareCheck(solved,0);
但是在运行几次并使用System.out.println()后,我发现它总是返回true;打印出 Set 后,我发现它只检查了第一个值,所以输出将是[5] true。
我的逻辑是否有问题,这就是为什么它总是返回 true,或者我还缺少什么?
【问题讨论】:
-
你得到的答案是正确的。另外
r和c,对于循环变量,都迭代到board[0].length。这对我来说似乎是错误的,因为r和c不在数组的同一维度中。