You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 validInput to track when we have a valid input + existing file. The loop runs until this flag is true.
  • Handling missing files: Instead of exiting, we use continue to jump back to the start of the loop and ask for input again.
  • Clearing invalid input: When InputMismatchException is thrown, the invalid input (like a string) stays in the scanner's buffer. Calling scan.nextLine() clears it, so the next scan.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 for IOException when reading the file (since Scanner(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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 18:02:34