Infinite loop when using scanner? [duplicate]

2019-02-20 17:50发布

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

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?

1条回答
Emotional °昔
2楼-- · 2019-02-20 18:40

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

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.

edit for Marcelo:

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

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!

查看更多
登录 后发表回答