Java中实现输入验证失败后回到输入语句重新执行的方案(含异常处理场景)
How to Retry Input Instead of Exiting the Program
Got it, let's refactor your code to keep asking for input until the user provides a valid number that corresponds to an existing .ics file. The key here is wrapping your input/validation logic in a loop, and handling both the input mismatch and missing file cases without exiting.
Here's the revised code:
import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.InputMismatchException; import java.util.Scanner; public class FileInputHandler { public static void main(String[] args) { short x = 0; Scanner scan = new Scanner(System.in); boolean validInput = false; // Loop until we get valid input + existing file while (!validInput) { try { System.out.print("Please enter a number: "); x = scan.nextShort(); Path path = Paths.get(x + ".ics"); if (!Files.exists(path)) { System.out.println("Sorry, file does not exist. Please try again."); continue; // Skip to next iteration of the loop } // If we reach here, input is valid and file exists validInput = true; } catch (InputMismatchException e) { System.out.println("Sorry, please enter a valid number."); scan.nextLine(); // Clear the invalid input from the scanner buffer } } // Now execute the code that comes after valid input File f = new File(x + ".ics"); try (Scanner classScan = new Scanner(f)) { byte i = 1; for (; i <= 6; i++) { if (classScan.findWithinHorizon(String.valueOf(i), 0) != null) { break; } } System.out.println("Found match at: " + i); } catch (IOException e) { // Handle potential file read errors (good practice!) System.out.println("Error reading the file: " + e.getMessage()); } scan.close(); } }
Key changes explained:
- Loop with a validation flag: We use
boolean validInputto track when we have a valid input + existing file. The loop runs until this flag istrue. - Handling missing files: Instead of exiting, we use
continueto jump back to the start of the loop and ask for input again. - Clearing invalid input: When
InputMismatchExceptionis thrown, the invalid input (like a string) stays in the scanner's buffer. Callingscan.nextLine()clears it, so the nextscan.nextShort()doesn't immediately throw the same exception again (this prevents an infinite loop!). - Proper resource cleanup: Added
scan.close()to clean up the scanner, and added a catch forIOExceptionwhen reading the file (sinceScanner(File)can throw it, which your original code didn't handle). - User prompts: Added a prompt asking the user to enter a number, which makes the program more user-friendly.
This approach keeps the program running until the user provides valid input, then proceeds to process the file as intended.
内容的提问来源于stack exchange,提问作者gooooodmorning
相关产品推荐
相关产品推荐

