我正在制作一个基于控制台的二十一点游戏,提示用户询问他/她是否想要:“h”表示命中,“s”表示停留,或“q”表示退出。我正在使用 Scanner 类在 while 循环中接收用户的输入。该代码在第一次提示用户并接收输入时有效,但第二次就不再有效。在第二个提示出现后,无论用户键入什么,程序都只是等待并且什么也不做,即使它仍在运行。我一直试图让它工作几个小时,并阅读了 Java Docs、许多 SO 问题等。以下是相关代码:
public void gameloop() {
while (thedeck.cards.size() >= 1) {
prompt();
}
}
public void prompt() {
String command = "";
Boolean invalid = true;
System.out.println("Enter a command - h for hit, s for stay, q for quit: ");
Scanner scanner = new Scanner(System.in);
while (invalid) {
if (scanner.hasNext()) {
command = scanner.next();
if (command.trim().equals("h")) {
deal();
invalid = false;
} else if (command.trim().equals("s")) {
dealerturn();
invalid = false;
} else if (command.trim().equals("q")) {
invalid = false;
System.exit(0);
} else {
System.out.println("Invalid input");
scanner.next();
}
}
}
scanner.close();
}
这是代码输出的内容:
Dealer has shuffled the deck.
Dealer deals the cards.
Player's hand:
Three of Clubs: 3
Five of Clubs: 5
Enter a command - h for hit, s for stay, q for quit:
h
Dealer deals you a card:
Player's hand:
Three of Clubs: 3
Five of Clubs: 5
Queen of Hearts: 10
Enter a command - h for hit, s for stay, q for quit:
h (Program just stops here, you can keep entering characters,
but it does nothing even though the code is still running)
任何关于出了什么问题的想法将不胜感激。我也意识到 while 循环有点难看,但我只想在开始修改任何代码之前让这个程序处于工作状态。