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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18678939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 10:06:37  来源:igfitidea点击:

How to check if the input is an integer?

java

提问by Nikhil

I am taking input as integer using Scanner class. like this:in.nextInt();I need to prompt "wrong input" if user has entered any floating point number or character or string. How can i accomplish this ?

我使用 Scanner 类将输入作为整数。像这样:in.nextInt();如果用户输入了任何浮点数或字符或字符串,我需要提示“错误输入”。我怎样才能做到这一点?

回答by Martijn Courteaux

Put it in a try-catch body.

把它放在一个 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);
}

回答by Sotirios Delimanolis

nextInt()can only return an intif the InputStreamcontains an intas the next readable token.

nextInt()int如果InputStream包含 anint作为下一个可读标记,则只能返回 an 。

If you want to validate input, you should use something like nextLine()to read a full String, and use Integer.parseInt(thatString)to check if it is an integer.

如果你想验证输入,你应该使用类似nextLine()读取 full 的东西String,并使用Integer.parseInt(thatString)它来检查它是否是一个整数。

The method will throw a

该方法将抛出一个

NumberFormatException- if the string does not contain a parsable integer.

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

回答by nasser-sh

As I mentioned in the comments, try using the try-catchstatement

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

int someInteger;

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