无限循环当在try-catch块中捕获InputMidmatchException时 [英] Infinite While Loop When InputMidmatchException is caught in try-catch block

查看:144
本文介绍了无限循环当在try-catch块中捕获InputMidmatchException时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



这是没有进展的,但我无法想象出我的生活! / p>

有人请帮助



我没有直接重新创建具体错误,而没有所有的if语句我的实际程序。

 包bs; 

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

public class bs {

public static void main(String [] args){

扫描仪sc = new Scanner(System.in);

boolean continueVar = true;

while(continueVar){

try {
System.out.println(Enter Something);
int input = sc.nextInt();

} catch(InputMismatchException i){
System.out.println(what the f ***?);
continueVar = true;
}
}


}
}

当捕获输入不匹配异常时,会发生无限循环。我会认为,至少要求用户重新输入他们的输入,而不是这样做,它只是在循环中继续:

 运行:
输入东西
df
什么是f ***?
输入东西
什么是f ***?
输入东西
什么是f ***?

它的行为就像只是忽略扫描仪对象sc?!

解决方案

不要跳过扫描仪,它只是从输入开始开始。从JavaDoc:


如果翻译成功,扫描仪将超过匹配的输入。


这意味着如果转换不成功,扫描仪不会提前。因此,您只需使用 next()手动跳过错误的输入。



编辑:您可能想要在尝试阅读输入之前检查 hasNextInt()


I keep getting my code caught in an infinite while loop.

It is nothing to advanced, but i can not figure it out for the life of me!

Someone Please help

I have purplosely just re created the specific error without all of the if statements i have in my actual program.

    package bs;

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

    public class bs {

        public static void main(String[] args) {

            Scanner sc = new Scanner(System.in);

            boolean continueVar = true;

            while (continueVar) {

                try {
                    System.out.println("Enter Something");
                    int input = sc.nextInt();

                } catch (InputMismatchException i) {
                    System.out.println("What the f***?");
                    continueVar = true;
                }
            }


        }
    }

The infinite loop occurs when the Input mismatch exception is caught. I would think that it would atleast ask the user to re enter their input but instead of doing that it just continues in the loop as so:

    run:
    Enter Something
    df
    What the f***?
    Enter Something
    What the f***?
    Enter Something
    What the f***?

It acts like it is just ignoring the scanner object sc?!

解决方案

No the scanner is not skipped, it's just starting at the beginning of the input. From the JavaDoc:

If the translation is successful, the scanner advances past the input that matched.

This means if the conversion isn't successfull the scanner won't advance. You'd thus have to manually skip the incorrect input using just next().

Edit: you might want to check for hasNextInt() before trying to read the input.

这篇关于无限循环当在try-catch块中捕获InputMidmatchException时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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