Java代码正常但数值超出范围场景异常,求问题排查方案
Fixing Your Java Input Validation Code
Let's walk through the issues in your code and get it working properly—right now, your code has critical syntax gaps and missing logic that's causing the range check failure (plus it won't even compile as-is!).
Key Problems in Your Original Code
- Incomplete do-while loop: You started a
doblock but never added the closingwhile(condition)statement, which is mandatory for the loop to function. - Missing catch block: A
tryblock must always be paired with at least onecatchorfinallyblock. Your code cuts off mid-try, which will throw a compile error. - No range validation logic: There's no code to check if the entered number is actually between 1 and 100, so the program has no way to react to invalid range inputs.
- Unfinished exception handling: The comment
//thr...suggests you intended to handle invalid ranges with an exception, but that code was never completed.
Fixed Complete Code
Here's a revised version that handles all cases—invalid integers, out-of-range values, and keeps prompting until valid input is received:
import java.util.InputMismatchException; import java.util.Scanner; public class Project11 { public static void main(String args[]) { int num = 0; Scanner kbd = new Scanner(System.in); do { try { System.out.print("Enter int in range 1..100 inclusive: "); num = kbd.nextInt(); // Check if the number is outside the valid range if (num < 1 || num > 100) { System.out.println("Oops! That number isn't between 1 and 100. Try again."); continue; // Skip the rest of the try block and loop again } // If we reach here, input is valid System.out.println("Great! You entered a valid number: " + num); } catch (InputMismatchException e) { System.out.println("Whoops! That's not an integer. Please enter a whole number."); // Clear the invalid input from the scanner buffer to avoid an infinite loop kbd.nextLine(); } } while (num < 1 || num > 100); // Keep looping until we get a valid number kbd.close(); // Clean up the scanner resource } }
What This Fixes
- Proper loop structure: The
do-whileloop now has a clear condition (num < 1 || num > 100) that keeps prompting until valid input is entered. - Range checking: We explicitly check if the number is outside 1-100 and give the user a clear error message.
- Non-integer input handling: The
catchblock catchesInputMismatchException(thrown when the user enters text instead of a number) and clears the scanner buffer to prevent an infinite loop. - Clean resource management: We close the
Scannerwhen we're done with it to avoid resource leaks.
内容的提问来源于stack exchange,提问作者Matt Cowell
相关产品推荐
相关产品推荐

