使用 InputMismatchException try/catch 创建无限循环 [英] try/catch with InputMismatchException creates infinite loop

查看:27
本文介绍了使用 InputMismatchException try/catch 创建无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在构建一个从用户输入中获取整数的程序.我有一个看起来非常简单的 try/catch 块,如果用户没有输入 int,应该重复该块直到他们输入.这是代码的相关部分:

So I'm building a program which takes ints from user input. I have what seems to be a very straightforward try/catch block which, if the user doesn't enter an int, should repeat the block until they do. Here's the relevant part of the code:

import java.util.InputMismatchException;
import java.util.Scanner;


public class Except {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        boolean bError = true;
        int n1 = 0, n2 = 0, nQuotient = 0;

        do {
            try {
                System.out.println("Enter first num: ");
                n1 = input.nextInt();
                System.out.println("Enter second num: ");
                n2 = input.nextInt();
                nQuotient = n1/n2;
                bError = false;
            } 
            catch (Exception e) {
                System.out.println("Error!");
            }
        } while (bError);

        System.out.printf("%d/%d = %d",n1,n2, nQuotient);
    }
}

如果我为第二个整数输入 0,那么 try/catch 会完全按照预期执行并让我再次输入.但是,如果我有一个 InputMismatchException,比如为其中一个数字输入 5.5,它只会在无限循环中显示我的错误消息.为什么会发生这种情况,我该怎么办?(顺便说一下,我已经尝试明确输入 InputMismatchException 作为要捕获的参数,但它没有解决问题.

If I enter a 0 for the second integer, then the try/catch does exactly what it's supposed to and makes me put it in again. But, if I have an InputMismatchException like by entering 5.5 for one of the numbers, it just shows my error message in an infinite loop. Why is this happening, and what can I do about it? (By the way, I have tried explicitly typing InputMismatchException as the argument to catch, but it didn't fix the problem.

推荐答案

出现错误时需要调用next();.另外建议使用 hasNextInt()

You need to call next(); when you get the error. Also it is advisable to use hasNextInt()

       catch (Exception e) {
            System.out.println("Error!");
           input.next();// Move to next other wise exception
        }

在读取整数值之前,您需要确保扫描仪有一个.您将不需要那样的异常处理.

Before reading integer value you need to make sure scanner has one. And you will not need exception handling like that.

    Scanner scanner = new Scanner(System.in);
    int n1 = 0, n2 = 0;
    boolean bError = true;
    while (bError) {
        if (scanner.hasNextInt())
            n1 = scanner.nextInt();
        else {
            scanner.next();
            continue;
        }
        if (scanner.hasNextInt())
            n2 = scanner.nextInt();
        else {
            scanner.next();
            continue;
        }
        bError = false;
    }
    System.out.println(n1);
    System.out.println(n2);

扫描仪的Javadoc

当扫描器抛出 InputMismatchException 时,扫描器不会传递导致异常的令牌,因此可以通过其他方法检索或跳过它.

When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.

这篇关于使用 InputMismatchException try/catch 创建无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆