Java 如何检查输入是否为整数?

Java 如何检查输入是否为整数?,java,Java,我使用Scanner类将输入作为整数。如下所示:in.nextInt() 如果用户输入了任何浮点数、字符或字符串,我需要提示“输入错误”。 我怎样才能做到这一点呢?把它放在一个try-catch主体中 String input = scanner.next(); int inputInt 0; try { inputInt = Integer.parseInt(input); } catch (Exception e) { System.out.println("Wrong inp

我使用Scanner类将输入作为整数。如下所示:
in.nextInt()
如果用户输入了任何浮点数、字符或字符串,我需要提示“输入错误”。

我怎样才能做到这一点呢?

把它放在一个try-catch主体中

String input = scanner.next();
int inputInt  0;
try
{
   inputInt = Integer.parseInt(input);
} catch (Exception e)
{
   System.out.println("Wrong input");
   System.exit(-1);
}
如果
InputStream
包含
int
作为下一个可读标记,则只能返回
int

如果要验证输入,应使用类似于
nextLine()
的方法读取完整的
字符串,并使用检查它是否为整数

该方法将抛出一个

NumberFormatException-如果字符串不包含可解析整数


正如我在评论中提到的,尝试使用
try-catch
语句

int someInteger;

try {
    someInteger = Scanner.nextInt();    
} catch (Exception e) {
    System.out.println("The value you have input is not a valid integer");
}

你有没有研究过try catch语句?你有没有读过关于扫描仪的文档?nextInt()
:?没有,我如何使用它来工作?@roliu
扫描仪#nextInt()
可能是最不可取的接收用户输入的方法,因为它缺乏健壮性。例如,如果用户输入了无法解析为整数的内容,程序将崩溃。@JoshM我不知道在java中读取用户输入的最流行标准是什么,但您可以清楚地防止
nextInt()
使程序崩溃。