java扫描器没有这样的元素例外
获取此代码:
private void runGame() {
boolean won = false;
while(won == false) {
System.out.println("DEBUG A");
Player p = this.nextPlayer();
System.out.println("DEBUG B");
Scanner s = new Scanner(System.in);
if(p.getPlayerType() == 0) {
System.out.println("DEBUG C");
// is Human
BoardPrinter.printBoard(this.b);
// Choose figure
BoardPrinter.printFigureChoose(this.b.getFiguresFromPlayer(p.getSymbol()),p);
int id = this.checkInput(1,this.b.getFiguresFromPlayer(p.getSymbol()).size(),s.nextInt());
Figure f = this.b.getFiguresFromPlayer(p.getSymbol()).get(id - 1);
// Choose move
ArrayList<Move> moves = b.checkMoves(f);
BoardPrinter.printMoveChoose(moves,p);
int moveID = this.checkInput(1,moves.size(),s.nextInt());
Move m = moves.get(moveID - 1);
// Execute the chosen move
this.b.getCellAt(f.getLocation().getX(), f.getLocation().getY()).setSymbol(Symbol.EMPTY);
f.setLocation(m.getTarget());
this.b.getCellAt(m.getTarget().getX(), m.getTarget().getY()).setSymbol(p.getSymbol());
// Check win conditions
won = this.checkVictory(p);
System.out.println("DEBUG D");
}
else {
// KI stuff
KI k = new KI(this.b,p,p.getPlayerType());
Move m = k.think();
// Execute chosen move
Figure f = this.b.getFigureAt(m.getStart());
this.b.getCellAt(m.getStart().getX(), m.getStart().getY()).setSymbol(Symbol.EMPTY);
f.setLocation(m.getTarget());
this.b.getCellAt(m.getTarget().getX(), m.getTarget().getY()).setSymbol(p.getSymbol());
}
// Decomment this to get debug info
//DebugPrinter.print(this.b);
s.close();
}
}
目前我确实得到了一个java。util。非接触性异常。是的,我知道我的意思,我在谷歌上搜索了很多。我还是不明白为什么它会被扔出去。而且,我只在“C”之前获得调试输出
如果我将扫描器初始化移到while循环之外,我就不会再出现这种异常。然而,我还是坚持这样做,代码在调试“A”时停止,其他什么都没有
当我有两个人类玩家时,我都遇到过这种情况。有趣的事实:第一个玩家将永远完美地工作。玩家可以看到棋盘,选择一个人物,选择一个动作并执行它。每当下一次while()运行开始,第二个播放器出现问题时,它就会失败,正如我在上面所描述的,这取决于扫描仪初始化的位置
猜猜有什么问题吗?非常感谢!:)
# 1 楼答案
在while循环结束时关闭扫描仪。这意味着下次尝试从扫描仪读取内容时,您将得到一个
NoSuchElementException