尝试catch阻塞导致无限循环? [英] Try catch block causing infinite loop?

查看:191
本文介绍了尝试catch阻塞导致无限循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个简单的java控制台游戏。我使用扫描仪从控制台读取输入。我试图验证它我要求一个整数,如果输入一个字母,我不会收到错误。我试过这个:

I am writing a simple java console game. I use the scanner to read the input from the console. I am trying to verify that it I ask for an integer, I don't get an error if a letter is entered. I tried this:

boolean validResponce = false;
int choice = 0;
while (!validResponce)
{
    try
    {
        choice = stdin.nextInt();
        validResponce = true;
    }
    catch (java.util.InputMismatchException ex)
    {
        System.out.println("I did not understand what you said. Try again: ");
    }
}

但它似乎创造了一个无限循环,只是打印挡住了。我做错了什么。

but it seems to create an infinite loop, just printing out the catch block. What am I doing wrong.

是的,我是Java新手

And yes, I am new to Java

推荐答案

nextInt()不会丢弃不匹配的输出;该程序将尝试一遍又一遍地读取它,每次都失败。使用 hasNextInt()方法确定在调用之前是否可以读取 int nextInt()

nextInt() won't discard the mismatched output; the program will try to read it over and over again, failing each time. Use the hasNextInt() method to determine whether there's an int available to be read before calling nextInt().

确保在 InputStream 中找到其他内容时你用 nextLine()清除它是一个整数,因为 hasNextInt()也不会丢弃输入,它只是测试输入流中的下一个标记。

Make sure that when you find something in the InputStream other than an integer you clear it with nextLine() because hasNextInt() also doesn't discard input, it just tests the next token in the input stream.

这篇关于尝试catch阻塞导致无限循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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