我有一個正在呼叫的函式,我希望它繼續回圈,但是當我接受輸入以繼續運行時,我收到以下錯誤:
Exception in thread "main"
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at SticksGame.main(SticksGame.java:144)
我認為這是由于我正在使用的掃描儀,但我不確定為什么在代碼中關閉兩個掃描儀時會出現問題。我嘗試洗掉其中一個掃描儀關閉,但隨后我的代碼無限回圈并要求相同的輸入。
public void begin() {
while (this.numOfSticks > 0) {
if (player == 1) {
doNextTurn(this.player);
} else if (player == 2 && !isAgainstAi) {
doNextTurn(this.player);
} else {
doAiNextTurn();
}
if (this.numOfSticks <= 0) {
if (this.player == 1 && isAgainstAi) {
// AI won
incrementHats(true);
}
if (this.player == 2 && isAgainstAi) {
System.out.println("AI loses.");
// AI loses
incrementHats(false);
// System.out.print("Play again (1 = yes, 0 = no)? ");
// int pA = scanner.nextInt();
// printHats();
} else {
String message = String.format("Player %s: you lose.", this.player);
System.out.println(message);
// printHats();
}
scanner.close();
return;
}
this.togglePlayer();
// printHats();
}
}
public static void main(String[] args) {
SticksGame game = new SticksGame();
Scanner s = new Scanner(System.in);
game.begin();
while (true) {
System.out.println("Play again (1 = yes, 0 = no)? ");
if (s.next().equals("1")) {
game.begin();
} else {
s.close();
System.exit(1);
}
}
}
uj5u.com熱心網友回復:
scanner方法中沒有什么begin()。如果您將其關閉,則不必關閉它main。
uj5u.com熱心網友回復:
來自 JavaDoc Scanner.close():“如果此掃描儀尚未關閉,那么如果其底層可讀也實作了 Closeable 介面,則將呼叫可讀的 close 方法。”
由于System.in是InputStream實作Closeable介面的,關閉掃描器也會關閉System.in流,因此會影響其他掃描器。NoSuchElementException如果您再次嘗試使用它,您會得到一個。
uj5u.com熱心網友回復:
Scanner.close()將關閉掃描儀本身以及任何底層可關閉物件。并且由于System.in由 JVM 內部管理,因此一旦關閉就無法重新打開它。您應該盡量避免關閉任何包裝System.in.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/466391.html
