简体   繁体   English

在 While 循环中处理 InputMismatchException

[英]Handling InputMismatchException in a While-Loop

So I have a while-loop where you have 3 options to choose from and you choose them by inserting a number on standard input using a scanner, my code is like this:所以我有一个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");
        }
    }

So the way this is the code enters in an infinite loop when it catches the exception where it keeps printing "Invalid input", I tried using input2.next() at the catch but then he waits for another input I don't want, I can't use input2.close() either.所以这是代码在捕获异常时进入无限循环的方式,它不断打印“无效输入”,我尝试在捕获时使用 input2.next() 但然后他等待另一个我不想要的输入,我也不能使用 input2.close() 。 What can I do?我能做什么?

I can't use input2.close() either.我也不能使用 input2.close() 。

You should never close the Scanner instance for System.in as it also closes the System.in .您永远不应该关闭System.inScanner实例,因为它也会关闭System.in

I tried using input2.next() at the catch but then he waits for another input I don't want我尝试在捕获时使用 input2.next() 但随后他等待另一个我不想要的输入

Use Scanner::nextLine instead of Scanner::next , Scanner::nextInt etc. Check Scanner is skipping nextLine() after using next() or nextFoo()?使用Scanner::nextLine而不是Scanner::next , Scanner::nextInt等。 检查Scanner 在使用 next() 或 nextFoo() 后是否跳过 nextLine()? to learn why.了解原因。

Also, try to use do...while wherever you need to ask the user to enter the data again in case of an invalid entry.此外,尝试使用do...while任何需要在输入无效的情况下要求用户再次输入数据的地方。

Given below is a sample code incorporating these points:下面给出了包含这些要点的示例代码:

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);
    }
}

A sample run:示例运行:

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

Feel free to comment in case of any further doubt/issue.如有任何进一步的疑问/问题,请随时发表评论。

Just Put the Scanner statement inside your try block只需将 Scanner 语句放在 try 块中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM