You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Hangman游戏空输入异常求助:StringIndexOutOfBoundsException

Fixing the Empty Input Exception in Your Hangman Game

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 calling charAt(0) on an empty string throws the StringIndexOutOfBoundsException—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

  1. 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.
  2. Safe Character Extraction: Since we check if inputStr is empty first, we know inputStr.charAt(0) will only run when there's at least one character present, completely eliminating the exception.
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:38:55