[英]How do I make sure User input integer type only and integer that is greater than 0?
I am attempting to make sure the user input int type only and make sure the integer inputted is greater than 0
. 我试图确保仅用户输入int类型,并确保输入的整数大于0
。
I was able to come up with the following to make sure the input is int type: 我能够提出以下内容以确保输入为int类型:
Scanner scan = new Scanner(System.in);
while(!scanner.hasNextInt())
{
scanner.next();
}
int input = scan.nextInt();
But how should I include a condition checking to make sure the integer is greater than 0 as well? 但是我应该如何包括条件检查以确保整数也大于0?
The problem with your current approach is you've already ready the value from the Scanner
before it reaches int input = scan.nextInt();
当前方法的问题是,在到达int input = scan.nextInt();
之前,您已经准备好了来自Scanner
的值int input = scan.nextInt();
, meaning that by the time you use nextInt
, there's nothing in the Scanner
to be read and it will wait for the next input from user... ,这意味着到您使用nextInt
, Scanner
中将没有任何内容要读取,它将等待用户的下一次输入...
Instead, you could read the String
from the Scanner
using next
, use Integer.parseInt
to try and parse the result to an int
and then check the result, for example... 相反,您可以使用next
从Scanner
读取String
,使用Integer.parseInt
尝试将结果解析为int
,然后检查结果,例如...
Scanner scanner = new Scanner(System.in);
int intValue = -1;
do {
System.out.print("Please enter a integer value greater than 0: ");
String next = scanner.next();
try {
intValue = Integer.parseInt(next);
} catch (NumberFormatException exp) {
}
} while (intValue < 0);
System.out.println("You input " + intValue);
put an if statement inside your while loop like this 像这样在您的while循环中放置一个if语句
if(num <= 0){
System.out.println("Enter a number greater than zero");
}
else{
break;
}
You may use a condition in your code but not in the loop as. 您可以在代码中使用条件,但不能在循环中使用条件。 ` `
Scanner scan = new Scanner(System.in);
abc:
while(!scanner.hasNextInt())
{
scanner.next();
}
int input = scan.nextInt();
if(input <= 0){
goto abc;
}
` `
使用.isDigit()方法,然后检查该数字是否大于0(如果是数字)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.