Reputation: 37
I am attempting to make sure the user input int type only and make sure the integer inputted is greater than 0
.
I was able to come up with the following to make sure the input is int type:
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?
Upvotes: 0
Views: 6729
Reputation: 294
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;
}
`
Upvotes: 0
Reputation:
put an if statement inside your while loop like this
if(num <= 0){
System.out.println("Enter a number greater than zero");
}
else{
break;
}
Upvotes: 0
Reputation: 347332
The problem with your current approach is you've already ready the value from the Scanner
before it reaches 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...
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...
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);
Upvotes: 2
Reputation: 29
using .isDigit() method then checking to see if that number is greater than 0 if it is a digit
Upvotes: -1