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

时间:2012-11-13 04:00:56

标签: java exception-handling

我一直试图阻止异常,但我无法弄清楚如何。 我尝试了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)

3 个答案:

答案 0 :(得分:2)

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

只要没有可用的整数(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.");
    }
}

答案 1 :(得分:1)

如何捕获异常的快速示例:

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

答案 2 :(得分:0)

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

请记住,您可能需要做一秒nextLine()(丢弃输入)以清除缓冲区。