在 While 循环中处理 InputMismatchException

Handling InputMismatchException in a While-Loop

所以我有一个 while 循环,你有 3 个选项可供选择,你可以通过使用扫描仪在标准输入上插入一个数字来选择它们,我的代码是这样的:

    int option;
    String request;
    Scanner input2 = new Scanner(System.in);
    System.out.println("Choose an option:\n" + "1-Get camera information\n" + "2-Submit Data\n"
         + "3-Exit");
    while(true){
        try {
            option = input2.nextInt();
            if (option == 1) {
                System.out.println("Camera name:");
                request = input2.nextLine();
                while (request.length() < 3 || request.length() > 15) {
                    System.out.println("Name has to be between 3 and 15 characters, insert a new one:");
                    request = input2.nextLine();
                }
                CamInfoRequest info_request = CamInfoRequest.newBuilder().setName(request).build();
                if (stub.camInfo(info_request).getReturn() != 0) {
                    System.out.println("Camera does not exist");
                } else {
                    System.out.println(stub.camInfo(info_request).getLatitude() + " " + stub.camInfo(info_request).getLongitude());
                }
            } else if (option == 2) {
                System.out.println("submit");
            } else if(option ==3){
                break;
            } else{
                System.out.println("Invalid option.");
            }
        }catch(InputMismatchException e){
            System.out.println("Invalid input");
        }
    }

所以这是代码进入无限循环的方式,当它捕捉到它不断打印的异常时 "Invalid input",我尝试在捕获时使用 input2.next() 但然后他等待另一个我不想要的输入,我也不能使用 input2.close() 。我能做什么?

只需将 Scanner 语句放入您的 try 块中

while (true) {
            try {
                Scanner input2 = new Scanner(System.in);
                option = input2.nextInt();
                if (option == 1) {

I can't use input2.close() either.

您永远不应该关闭 System.inScanner 实例,因为它也会关闭 System.in.

I tried using input2.next() at the catch but then he waits for another input I don't want

使用 Scanner::nextLine 而不是 Scanner::nextScanner::nextInt 等。检查 Scanner is skipping nextLine() after using next() or nextFoo()? 了解原因。

另外,在输入无效的情况下需要要求用户再次输入数据的地方尝试使用 do...while

下面给出了包含这些要点的示例代码:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int option;
        boolean valid;
        Scanner input2 = new Scanner(System.in);
        do {
            valid = true;
            System.out.println("Choose an option:\n" + "1-Get camera information\n" + "2-Submit Data\n" + "3-Exit");
            try {
                option = Integer.parseInt(input2.nextLine());
                if (option < 1 || option > 3) {
                    throw new IllegalArgumentException();
                }
                // ...Place here the rest of code (which is based on the value of option)
            } catch (IllegalArgumentException e) {
                System.out.println("This is an invalid entry. Please try again.");
                valid = false;
            }
        } while (!valid);
    }
}

样本运行:

Choose an option:
1-Get camera information
2-Submit Data
3-Exit
abc
This is an invalid entry. Please try again.
Choose an option:
1-Get camera information
2-Submit Data
3-Exit
6
This is an invalid entry. Please try again.
Choose an option:
1-Get camera information
2-Submit Data
3-Exit
2

如有任何进一步的问题,请随时发表评论doubt/issue。