Java 如何检查用户输入是否不是 int 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18119211/
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
How to check if user input is not an int value
提问by jjkk0990
I need to check if a user input value is not an int value. I've tried different combinations of what I know but I either get nothing or random errors
我需要检查用户输入值是否不是 int 值。我尝试了我所知道的不同组合,但我要么一无所获,要么出现随机错误
For example:
例如:
If the user inputs "adfadf 1324" it'll raise a warning message.
如果用户输入“adfadf 1324”,它会发出警告消息。
What I have:
我拥有的:
// Initialize a Scanner to read input from the command line
Scanner sc = new Scanner(System.in);
int integer, smallest = 0, input;
boolean error = false;
System.out.print("Enter an integer between 1-100: ");
range = sc.nextInt();
if(!sc.hasNextInt()) {
error = true;
System.out.println("Invalid input!");
System.out.print("How many integers shall we compare? (Enter an integer between 1-100: ");
sc.next();
}
while(error) {
for(int ii = 1; ii <= integer; ii++) {
...
} // end for loop
}
System.out.println("The smallest number entered was: " + smallest);
}
}
采纳答案by Pandiyan Cool
Simply throw Exception if input is invalid
如果输入无效,只需抛出异常
Scanner sc=new Scanner(System.in);
try
{
System.out.println("Please input an integer");
//nextInt will throw InputMismatchException
//if the next token does not match the Integer
//regular expression, or is out of range
int usrInput=sc.nextInt();
}
catch(InputMismatchException exception)
{
//Print "This is not an integer"
//when user put other than integer
System.out.println("This is not an integer");
}
回答by ElliotSchmelliot
Taken from a related post:
摘自相关帖子:
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
}
// only got here if we didn't return false
return true;
}
回答by Rajendra_Prasad
Try this one:
for (;;) {
if (!sc.hasNextInt()) {
System.out.println(" enter only integers!: ");
sc.next(); // discard
continue;
}
choose = sc.nextInt();
if (choose >= 0) {
System.out.print("no problem with input");
} else {
System.out.print("invalid inputs");
}
break;
}
回答by Rajendra_Prasad
you have following errors which in turn is causing you that exception, let me explain it
您有以下错误,这反过来又导致您出现异常,让我解释一下
this is your existing code:
这是您现有的代码:
if(!scan.hasNextInt()) {
System.out.println("Invalid input!");
System.out.print("Enter an integer: ");
usrInput= sc.nextInt();
}
in the above code if(!scan.hasNextInt())
will become true
only when user input contains both characters as well as integers like your input adfd 123
.
在上面的代码中,只有当用户输入既包含字符又包含整数时if(!scan.hasNextInt())
才会变为true
输入 adfd 123
。
but you are trying to read only integers inside the if condition using usrInput= sc.nextInt();
. Which is incorrect,that's what is throwing Exception in thread "main" java.util.InputMismatchException
.
但是您正在尝试使用 usrInput= sc.nextInt();
. 这是不正确的,这就是 throw Exception in thread "main" java.util.InputMismatchException
。
so correct code should be
所以正确的代码应该是
if(!scan.hasNextInt()) {
System.out.println("Invalid input!");
System.out.print("Enter an integer: ");
sc.next();
continue;
}
in the above code sc.next()
will help to read new input from user and continue
will help in executing same if condition(i.e if(!scan.hasNextInt())
) again.
在上面的代码sc.next()
中将有助于从用户读取新输入,并 continue
有助于i.e if(!scan.hasNextInt())
再次执行相同的 if 条件()。
Please use code in my first answer to build your complete logic.let me know if you need any explanation on it.
请使用我的第一个答案中的代码来构建您的完整逻辑。如果您需要任何解释,请告诉我。
回答by Rajendra_Prasad
try this code [updated]:
试试这个代码[更新]:
Scanner scan = null;
int range, smallest = 0, input;
for(;;){
boolean error=false;
scan = new Scanner(System.in);
System.out.print("Enter an integer between 1-100: ");
if(!scan.hasNextInt()) {
System.out.println("Invalid input!");
continue;
}
range = scan.nextInt();
if(range < 1) {
System.out.println("Invalid input!");
error=true;
}
if(error)
{
//do nothing
}
else
{
break;
}
}
for(int ii = 1; ii <= range; ii++) {
scan = new Scanner(System.in);
System.out.print("Enter value " + ii + ": ");
if(!scan.hasNextInt()) {
System.out.println("Invalid input!");
ii--;
continue;
}
}
回答by shady
Maybe you can try this:
也许你可以试试这个:
int function(){
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer between 1-100: ");
int range;
while(true){
if(input.hasNextInt()){
range = input.nextInt();
if(0<=range && range <= 100)
break;
else
continue;
}
input.nextLine(); //Comsume the garbage value
System.out.println("Enter an integer between 1-100:");
}
return range;
}
回答by Salah Assaf
This is to keep requesting inputs while this input is integer and find whether it is odd or even else it will end.
这是为了在此输入为整数时继续请求输入,并查找它是奇数还是偶数,否则它将结束。
int counter = 1;
System.out.println("Enter a number:");
Scanner OddInput = new Scanner(System.in);
while(OddInput.hasNextInt()){
int Num = OddInput.nextInt();
if (Num %2==0){
System.out.println("Number " + Num + " is Even");
System.out.println("Enter a number:");
}
else {
System.out.println("Number " + Num + " is Odd");
System.out.println("Enter a number:");
}
}
System.out.println("Program Ended");
}