开发者

Infinite loop when using scanner? [duplicate]

This qu开发者_运维技巧estion already has answers here: How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner (5 answers) Closed 6 years ago.
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?


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜