Switch方法异常处理:Java程序如何处理1-13范围外的无效输入?
Fixing Input Validation for Your Java Unit Selection Program
Hey Dan, let's tackle that input handling problem you're facing. Right now, your code only catches NullPointerException, but it's missing two critical scenarios: non-integer inputs (like letters or symbols) and integer inputs outside the 1-13 range. Here's a step-by-step solution to cover all edge cases:
Key Issues in Your Current Code
input.nextInt()throws an InputMismatchException when the user enters something that's not an integer (not aNullPointerException), so your current catch block won't trigger for those cases.- Even if the user enters an integer, if it's outside 1-13,
selectUnit()returns null—but you don't explicitly validate the range before calling the method, leading to unexpected nulls. - Without clearing the Scanner buffer after invalid input, you'll get an infinite loop of exceptions.
Modified Code with Full Input Validation
import java.util.InputMismatchException; import java.util.Scanner; // Assume this is your Unit class (adjust as needed) class Unit { private String unitName; public Unit(String name) { this.unitName = name; } public String getUnitName() { return unitName; } } public class UnitSelectionHandler { public Unit selectUnit(int choice) { // Validate range first before returning a Unit if (choice >= 1 && choice <= 13) { return new Unit("Unit " + choice); } return null; // Return null for out-of-range inputs } public void showUnitSelection() { System.out.println("=== Unit Selection ==="); System.out.println("Please enter a number between 1 and 13 to choose your unit:"); } public void getAttackingUnit(Scanner input) { Unit attackingUnit = null; String attackerUnitName = null; // Loop until valid input is received while (attackingUnit == null) { showUnitSelection(); try { int userChoice = input.nextInt(); attackingUnit = selectUnit(userChoice); if (attackingUnit == null) { // Handle out-of-range integer input System.out.println("\n❌ Invalid range! Please pick a number between 1 and 13.\n"); } else { attackerUnitName = attackingUnit.getUnitName(); System.out.println("\n✅ Selected unit: " + attackerUnitName); } } catch (InputMismatchException e) { // Handle non-integer input (letters, symbols, etc.) System.out.println("\n❌ Invalid input! Please enter a whole number (1-13).\n"); input.nextLine(); // Clear invalid input from Scanner buffer to avoid infinite loop } // Note: The NullPointerException catch is removed here because we explicitly check for null // If selectUnit() could throw NPE for other reasons, you can add it back, but range checks cover most cases } } }
Critical Improvements Explained
- Catch
InputMismatchException: This is the main exception thrown whennextInt()encounters non-integer input—this was the big gap in your original code. - Clear the Scanner Buffer:
input.nextLine()after catching the exception ensures the invalid input is discarded, so the Scanner is ready to read new input in the next loop iteration. - Explicit Range Validation: Instead of relying on
NullPointerExceptionto catch out-of-range values, we check ifselectUnit()returns null and give a specific error message (more user-friendly). - Loop Until Valid Input: The
whileloop keeps prompting the user until they enter a valid option, so they don't have to restart the selection process manually.
Optional Enhancements
- Add a maximum number of retries (e.g., 3 attempts) before exiting the selection flow.
- Use
input.hasNextInt()to pre-check if the next input is an integer, avoiding exceptions entirely (a more proactive approach):if (!input.hasNextInt()) { System.out.println("\n❌ Invalid input! Please enter a whole number.\n"); input.nextLine(); continue; } int userChoice = input.nextInt();
内容的提问来源于stack exchange,提问作者Dan
相关产品推荐
相关产品推荐

