检查输入值是否为整数类型java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19795808/
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
Checking if the input value is integer type java
提问by Edgars
I am requesting users input where he needs to write integers. I managed to create validation that checks if the value is higher than needed and so, with this code :
我要求用户输入他需要写整数的地方。我设法创建验证,检查值是否高于需要的值,因此,使用以下代码:
int n = sca.nextInt();
while (n<=0){
System.err.println(error_1);
n = sca.nextInt();
}
But now how to add check for strings, I found such solution How do I keep a Scanner from throwing exceptions when the wrong type is entered?
但是现在如何添加对字符串的检查,我找到了这样的解决方案如何在输入错误类型时防止扫描仪抛出异常?
That uses hasNextInt()
before actually reading the input, I tried to put this check inside while loop in the same place with n<=0
like this
hasNextInt()
在实际读取输入之前使用,我尝试将此检查放入 while 循环中的同一位置,n<=0
如下所示
while ( (n<=0)||(sca.hasNextInt() )) {
....
}
But it responded with error that variable n
is not compatible with that method.
So is there any way to overcome such thing?
但它以错误响应变量n
与该方法不兼容。那么有没有办法克服这样的事情呢?
采纳答案by lkamal
First invocation of nextInt()
also can result in an exception, if you do not check whether the input is of int
type.
nextInt()
如果不检查输入是否属于int
类型,则首次调用也可能导致异常。
Hope below will resolve your issue.
希望下面能解决您的问题。
Scanner sca = new Scanner(System.in);
boolean incorrectInput = true;
int userInput = -1; // initialize as a negative
while (incorrectInput) {
if (sca.hasNextInt()) {
int n = sca.nextInt();
if (n < 0) {
System.err.println("error_1");
} else {
// do anything else
userInput = n;
incorrectInput = false;
}
} else {
sca.next();
}
}
if (!incorrectInput) {
System.out.println("UserInput = " + userInput);
}
回答by Simulant
You have to test if there is a next Int before trying to get the next Int.
在尝试获取下一个 Int 之前,您必须测试是否有下一个 Int。
boolean finished = false;
while(!finished){
while(scan.hasNextInt()){
int n = sca.nextInt();
if(n <= 0){
System.out.println("Error: Number smaller 0");
} else {
System.out.println("correct!");
finished = true;
}
}
}
回答by ArturSkowronski
You can use parseInt and check exception:
您可以使用 parseInt 并检查异常:
public boolean parseWithFallback(String text) {
try {
Integer.parseInt(text);
return true;
} catch (NumberFormatException e) {
return false;
}
}
回答by Julian Kolodzey
You can request and validate user input as many times as need to do it right.
您可以根据需要多次请求和验证用户输入以正确执行。
private int readUserInput(String messageToUser) {
System.out.print("Enter " + messageToUser);
Scanner scan = new Scanner(System.in);
boolean validInput = false;
int res = 0;
do {
try {
validInput = scan.hasNextInt();
if (!validInput) {
throw new NotIntUserInputException();
}
res = scan.nextInt();
if (res < 1) {
validInput = false;
throw new NotPositiveIntUserInputException();
}
} catch (Exception e) {
System.out.print(e.getMessage());
scan.next();
}
} while (!validInput);
return res;
}
You have to create 2 classes NotIntUserInputException and NotPositiveIntUserInputException that are inheriting Exception class
您必须创建两个继承 Exception 类的类 NotIntUserInputException 和 NotPositiveIntUserInputException