Java.util.scanner error handling

谁说胖子不能爱 提交于 2019-12-09 17:56:40

问题


I'm helping a friend with a java problem. However, we've hit a snag. We're using Java.Util.Scanner.nextInt() to get a number from the user, asking continiously if the user gives anything else. Only problem is, we can't figure out how to do the error handeling.

What we've tried:

do {
  int reloop = 0;
  try {
    number = nextInt(); 
  } catch (Exception e) {
    System.out.println ("Please enter a number!");
    reloop ++; 
  }
} while(reloop != 0);

Only problem is, this loops indefinatly if you enter in something not a number.

Any help?


回答1:


You can use hasNextInt() to verify that the Scanner will succeed if you do a nextInt(). You can also call and discard nextLine() if you want to skip the "garbage".

So, something like this:

Scanner sc = new Scanner(System.in);
while (!sc.hasNextInt()) {
   System.out.println("int, please!");
   sc.nextLine();
}
int num = sc.nextInt();
System.out.println("Thank you! (" + num + ")");

See also:

  • How do I keep a scanner from throwing exceptions when the wrong type is entered? (java)

The problem with your code, in addition to the unnecessarily verbose error handling because you let nextInt() throw an InputMismatchException instead of checking for hasNextInt(), is that when it does throw an exception, you don't advance the Scanner past the problematic input! That's why you get an infinite loop!

You can call and discard the nextLine() to fix this, but even better is if you use the exception-free hasNextInt() pre-check technique presented above instead.




回答2:


if the number is non-int , exception will pop, if not reloop will become 1 , and loop will exit

  int reloop = 0;
  do {
   try {
        number = nextInt();
        reloop ++; 
  } catch (Exception e) {
       System.out.println ("Please enter a number!");
  }}
 while(reloop == 0);


来源:https://stackoverflow.com/questions/2696063/java-util-scanner-error-handling

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