伙计我在我正在寻找的内部和周围看到很多Q / A,但不是我正在寻找的。
情况:我正在阅读文件中的suduko谜题..首先我通过一个verify()方法运行它们,然后我调用下一个并检查每个(预期的)81个数字,以确保它们介于1和9.然后我将我的运行计数与81进行比较。只要计数== 81,我就知道至少有一个难题可以解决..当我尝试使用nextInt()重新访问流时[这次是将每个分配到suduko数组中]程序崩溃报告NoSuchElement。
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at edu.dccc.dpr212.suduko.SudokuPuzzle.<init>(SudokuPuzzle.java:31)
at edu.dccc.dpr212.suduko.Sudoku.main(Sudoku.java:30)
有些人说尝试访问已关闭的流会导致此错误,但我从不关闭该流。我在main中打开文件,并将其作为参数传递给构造函数,然后构造函数将其传递给在扫描程序上调用nextInt()的verify(扫描程序输入)方法,然后构造函数再次访问它[使用nextInt() ]将数字分配给拼图。
我认为正在发生的事情是验证方法耗尽了nextInt方法并且它永远不会重置..这可能吗?我怎么能绕过这个?我是否过多地通过扫描仪?
代码如下:
public SudokuPuzzle(Scanner input)
{
//verify puzzle FORMAT is correct
if (verifyPuzzle(input)) {
//Load Numbers Into Puzzle Array
for (int row = 0; row < 9; row++){
for (int column = 0; column < 9; column++) {
grid[row][column] = input.nextInt();
}
}
}
}
/**Verify Puzzle Is Valid Before Attempting To Solve
*
* @param input (file)
* @return true if puzzle is valid
*/
public boolean verifyPuzzle(Scanner input) {
boolean isVerified = false;
int temp = 0, count = 0;
while (!input.hasNextInt() == false) {
temp = input.nextInt();
// Are Numbers Within Range (1 - 9)?
if (temp > 9 || temp < 0)
{
System.out.println ("Puzzle Is Invalid. " + temp + " is an invalid number in Suduko.");
count--; //Ensures that last number will not generate valid puzzle count and return puzzle as valid
break;
}
count++;
}
//Are There Enough Numbers?
if (count != 81)
System.out.println ("Puzzle Is Invalid. Does Not Contain 81 Numbers");
else
isVerified = true;
return isVerified;
}