如何使用hasNextInt捕获异常?我需要整数,但是如果输入是字符,那是不好的

问题描述

在我看来,您想跳过所有内容,直到获得整数。此代码在这里跳过除整数以外的所有输入。

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

解决方法

我一直在试图阻止例外,但我不知道怎么办。我尝试过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)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...