如何使用hasNextInt()来捕获exception? 我需要Int,但如果输入是字符,那就很糟糕

我一直试图阻止例外,但我无法弄清楚如何。 我试过parseIntjava.util.NormalExceptionMismatch等。

有没有人有任何见解如何解决这个问题? 由于复制和粘贴,格式化有点偏。

 do { System.out.print( "How many integers shall we compare? (Enter a positive integer):"); select = intFind.nextInt(); if (!intFind.hasNextInt()) intFind.next(); { // Display the following text in the event of an invalid input System.out.println("Invalid input!"); } }while(select < 0) 

我试过的其他方法:

  do { System.out.print( "How many integers shall we compare? (Enter a positive integer):"); select = intFind.nextInt(); { try{ select = intFind.nextInt(); }catch (java.util.InputMismatchException e) { // Display the following text in the event of an invalid input System.out.println("Invalid input!"); return; } } }while(select < 0) 

在我看来,你想跳过一切,直到你得到一个整数。 这里的代码跳过除整数之外的任何输入。

只要没有可用的整数(while(!in.hasNextInt()))就丢弃可用的输入(in.next)。 当整数可用时 – 读取它(int num = in.nextInt();)

 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (!in.hasNextInt()) { in.next(); } int num = in.nextInt(); System.out.println("Thank you for choosing " + num + " today."); } } 

如何捕获exception的快速示例:

 int exceptionSample() { int num = 0; boolean done = false; while(!done) { // prompt for input // inputStr = read input try { num = Integer.parseInt(inputStr); done = true; } catch(NumberFormatException ex) { // Error msg } } return num; } 

IMO,最好的做法是使用nextLine()来获取String输入,然后使用parseInt获取整数。 如果不可解决,只需向用户投诉并请求重新进入。

请记住,您可能需要执行第二次nextLine() (丢弃输入)以清除缓冲区。