私はコンソール ベースのブラック ジャック ゲームを作成しています。このゲームでは、「h」でヒット、「s」で停止、または「q」で終了するかどうかをユーザーに尋ねます。Scanner クラスを使用して、while ループでユーザーからの入力を受け取ります。このコードは、最初にユーザーにプロンプトを表示して入力を受け取ったときに機能しますが、2 回目は機能しません。2 番目のプロンプトが表示された後は、ユーザーが何を入力しても、プログラムはそのまま待機し、実行中であっても何もしません。私はこれを何時間も機能させようとしており、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 ループが少し見にくいことも認識していますが、コードの修正を開始する前に、このプログラムを動作状態にしたいだけです。