使用扫描仪时无限循环? [英] Infinite loop when using scanner?

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

问题描述

boolean z = false;
do {
    try {
        a = sc.nextInt();
        z = true;
    }
    catch(Exception e) {
    }
}
while(!z);

试试这个。如果在第一次正确执行时尝试整数。但是,如果输入错误的文本类型,即使您输入int next并跳过将布尔值赋值为true,它也会变为无限循环。这是为什么?

Try this. If you try an integer the first time it executes properly. However if you enter the wrong type of text it turns into an infinite loop even if you enter an int next and skips assigning the boolean value to true. Why is this?

推荐答案

您的问题是由于没有处理行尾令牌而导致扫描仪挂起。你想做这样的事情:

Your problem is from not handling the end of line token and so the scanner is left hanging. You want to do something like so:

import java.util.Scanner;

public class Foo2 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = 0;
        boolean catcher = false;
        do {
            try {
                System.out.print("Enter a number: ");
                a = sc.nextInt();
                catcher = true;
            } catch (Exception e) {
            } finally {
                sc.nextLine();
            }

        }
        // !!while(catcher == false);
        while (!catcher);

        System.out.println("a is: " + a);
    }
}

此外,虽然(z == false)不好形成。在(!z)时你会好多了。这可以防止while(z = false)错误,并且是一种更清晰的表达方式。

Also, while (z == false) is bad form. You're much better off with while (!z). This prevents the while (z = false) error, and is a cleaner way of expressing this.

编辑Marcelo:

Marcelo,感谢您的意见和建议!你是说下面的if块中的条件不会改变布尔值,垃圾邮件的值吗?

Marcelo, thanks for your input and advice! Are you saying that the conditional in the if block below will not change the value of the boolean, spam?

  boolean spam = true;

  if (spam = false) {
     System.out.println("spam = false");
  }

  System.out.printf("spam = %b%n", spam);

因为如果它确实改变了它,编码器就不会期望这个如果他们打算写的话if(垃圾邮件== false),然后可能会出现微妙而危险的副作用。再次感谢您帮我澄清这一点!

Because if it does change it, the coder wouldn't expect this if they intended to write if (spam == false), then there could be subtle and dangerous side effects from this. Again, thanks for helping to clarify this for me!

这篇关于使用扫描仪时无限循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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