Scanner(System.in) - infinite loop

℡╲_俬逩灬. 提交于 2019-12-12 04:25:48

问题


Why I'm getting infinite loop in recursion method, without a chance to input any symbol to break it?

class Test {
   int key=0;
   void meth(){
     System.out.println("Enter the number here: ");
     try(Scanner scan = new Scanner(System.in)) {
        key = scan.nextInt();
        System.out.println(key+1);
     } catch(Exception e) {
        System.out.println("Error");
        meth();
     }
   }
}

class Demo {
  main method {
    Test t = new Test();
    t.meth();
  }
} 

If you try to create an error (putting string value in key and then try to add to it a number), you will get infinite "Error" text in console, instead of that, after first error, program should ask again the number and only then decide what to do.


回答1:


If nextInt() fails, it throws an exception but doesn't consume the invalid data. From the documentation:

When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.

You're then recursively calling meth() again, which will try to consume the same invalid data a second time, fail again (without consuming it), and recurse.

Firstly, I wouldn't use recursion here in the first place. Prefer a simple loop. Next, if you have invalid input you should consume it appropriately before trying again. Finally, consider using hasNextInt instead of just using nextInt and catching the exception.

So maybe something like this:

import java.util.Scanner;

class Test {
   public static void main(String[] args){
       try (Scanner scanner = new Scanner(System.in)) {
           System.out.println("Enter the number here:");
           while (!scanner.hasNextInt() && scanner.hasNext()) {
               System.out.println("Error");
               // Skip the invalid token
               scanner.next();
           }
           if (scanner.hasNext()) {
               int value = scanner.nextInt();
               System.out.println("You entered: " + value);
           } else {
               System.out.println("You bailed out");
           }
       }
   }
}


来源:https://stackoverflow.com/questions/28588022/scannersystem-in-infinite-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!