Note that there are some explanatory texts on larger screens.

plurals
  1. POJava: User Input - Scanner - Program Hangs After Second Input
    primarykey
    data
    text
    <p>I'm making a console-based game of black jack that prompts the user asking him/her if he/she wants to: 'h' for hit, 's' for stay, or 'q' for quit. I'm using the Scanner class to receive input from the user in a while loop. The code works the first time it prompts the user and receives input, but it never works the second time. After the second prompt comes up, no matter what the user types, the program just waits and does nothing even though it's still running. I've been trying to get this to work for hours and have read the Java Docs, many SO questions, etc. Here's the relevant code:</p> <pre><code>public void gameloop() { while (thedeck.cards.size() &gt;= 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(); } </code></pre> <p>Here's what the code outputs:</p> <pre><code>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) </code></pre> <p>Any idea as to what's going wrong would be greatly appreciated. I also realize the while loop is a little ugly, but I just want to get this program in working condition before I start to revamp any code.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload