如何为仅接受整数的Java成绩计算程序添加Q/q退出例外逻辑
Hey there! I see the problem you're facing—your current code is locked into expecting integer inputs right away, so when someone types Q or q, it just gets caught in the "invalid input" loop instead of triggering the quit. The fix is to read input as a string first so we can check for the quit command before trying to parse it as an integer.
Here's the revised code that handles both integer validation and the quit functionality:
import java.util.Scanner; public class Main { public static void main(String[] args) { boolean run = true; Scanner input = new Scanner(System.in); // Move scanner outside the loop to avoid reinitializing it while (run) { System.out.print("Enter the test score (or Q/q to quit): "); String userInput = input.nextLine().trim(); // Read input as a string and trim whitespace // Check for quit command first if (userInput.equalsIgnoreCase("q")) { run = false; System.out.println("Exiting program..."); continue; } // Now try to parse the input as an integer try { int tS = Integer.parseInt(userInput); int sum = 10 + tS; System.out.println("Calculated sum: " + sum); } catch (NumberFormatException e) { // If parsing fails, show error message System.out.println("Only number input is allowed! Or type Q/q to quit."); } } input.close(); // Clean up the scanner resource } }
Key Changes Explained:
- Read input as string: Using
nextLine()lets us capture any input the user types, includingQ/q, before deciding how to handle it. - Quit check first: We check if the input matches
Qorq(case-insensitive withequalsIgnoreCase()) immediately—if yes, we exit the loop. - Integer parsing with try-catch: We use
Integer.parseInt()inside a try-catch block to validate if the string is a valid integer. If not, we show the error message. - Scanner initialization: Moved the
Scanneroutside the while loop so we don't create a new scanner instance every iteration (better practice for resource management).
Why your original approach didn't work:
Your code used hasNextInt() which only returns true if the next input is an integer. When you typed Q, hasNextInt() returned false, so it entered the error loop and called input.next() to discard the invalid input—you never got a chance to check if that invalid input was the quit command.
内容的提问来源于stack exchange,提问作者Dark Apostle

