Hangman游戏空输入异常求助:StringIndexOutOfBoundsException
Hey there! Let's squash that frustrating empty input bug in your Hangman game right away. The root of the problem is exactly what you suspected: you're calling scanner.nextLine() twice in your input handling logic, which makes the program read two separate lines of input instead of one. Here's how to fix it step by step.
Why the Exception Happens
When you run your original code:
if (scanner.nextLine().isEmpty()) { System.out.println("Your guess seems empty. Please enter in a letter or number"); } else { char input = scanner.nextLine().charAt(0); // ... rest of your logic }
- The first
scanner.nextLine()reads your first input line to check if it's empty. - If it's not empty, the code calls
scanner.nextLine()again, which forces the program to wait for a second input line. - When you then enter an empty line the second time,
scanner.nextLine()returns an empty string, and callingcharAt(0)on an empty string throws theStringIndexOutOfBoundsException—because there's no character at index 0 to access.
The Simple Fix
Instead of calling scanner.nextLine() multiple times, read the input once and store it in a variable. Then use that variable for all your checks and processing:
while (!wordCompleted && attempts != 0) { printArray(playerGuess); System.out.println("Number of attempts left: " + attempts); System.out.println("Your previous guesses were:" + guessedLetters); System.out.println("Enter a letter or number"); // Read input ONCE and store it in a variable String inputStr = scanner.nextLine(); if (inputStr.isEmpty()) { System.out.println("Your guess seems empty. Please enter in a letter or number"); } else { char input = inputStr.charAt(0); if (input == '-' || Character.isLetter(input) || Character.isDigit(input)) { if (input == '-') { weArePlaying = false; wordCompleted = true; } // ... rest of your existing logic for valid guesses } else { // Optional: Add feedback for invalid character types System.out.println("Invalid input! Please enter a letter, number, or '-' to quit."); } } }
Key Changes Explained
- Single Input Read: We capture the user's input once into
inputStr—this ensures we only process one line of input per loop iteration, no more double-input prompts. - Safe Character Extraction: Since we check if
inputStris empty first, we knowinputStr.charAt(0)will only run when there's at least one character present, completely eliminating the exception. - Clearer User Feedback: I added an optional else clause to handle non-empty but invalid characters (like symbols) to make the game's instructions more intuitive—feel free to tweak or remove this if it doesn't fit your game's flow.
This adjustment will keep your game running smoothly: empty inputs trigger the friendly reminder without breaking the game, and valid inputs are processed correctly on the first try.
内容的提问来源于stack exchange,提问作者Merlin

