如何实现可处理文本输入的Do While循环,使输入非法文本时返回循环重新输入
Got it, let's tackle this problem head-on. The issue with your current code is that when someone enters a non-numeric value like "zero", the nextDouble() method throws an InputMismatchException and crashes the program—plus, the invalid input stays stuck in the Scanner's buffer, so even if you tried to loop again, it would keep reading that same bad input forever.
Here's a revised version of your code that handles both invalid text inputs AND negative/zero values, while keeping the user stuck in the loop until they enter a valid positive number:
import java.util.InputMismatchException; import java.util.Scanner; public class WallHeightInput { public static void main(String[] args) { Scanner scnr = new Scanner(System.in); double wallHeight = 0.0; boolean isValidInput = false; do { try { System.out.println("Enter wall height (feet): "); wallHeight = scnr.nextDouble(); // Check if the number is positive if (wallHeight > 0) { isValidInput = true; } else { System.out.println("Error: Height must be greater than 0. Please try again."); } } catch (InputMismatchException e) { // Handle non-numeric input System.out.println("Error: That's not a valid number. Please enter a numeric value."); // Clear the invalid input from the Scanner buffer scnr.nextLine(); } } while (!isValidInput); // Once valid input is received, proceed with your logic System.out.println("Valid wall height entered: " + wallHeight + " feet"); scnr.close(); } }
Let me break down what's happening here:
- We added a
boolean isValidInputflag to track when we have valid input. This gives us more control over the loop condition than just checkingwallHeight <=0. - Wrapped the input line in a
try-catchblock to catch theInputMismatchExceptionthat gets thrown when non-numeric text is entered. - When an exception is caught, we print an error message AND call
scnr.nextLine()to clear the invalid input from the scanner's buffer—this is crucial because without it, the scanner will keep trying to read the same bad text over and over. - We still check if the numeric input is positive, and if not, we prompt the user to try again without exiting the loop.
This way, whether the user enters "zero", "abc", or a negative number, they'll get a clear error message and be sent back to enter a valid value until they get it right.
内容的提问来源于stack exchange,提问作者Seth

