0

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?

1
  • You check the value. Commented Sep 8, 2014 at 0:20

4 Answers 4

2

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);
Sign up to request clarification or add additional context in comments.

4 Comments

Does this check the User input is of type Integer?
Integer.parseInt will do it's own internal checking, throwing an Exception if the value can not be parsed to an int value. You can not read and check for an int at the same time using Scanner
What does intValue = -1 represent?
In my example, intValue is initialised to -1 so that it will cause while (intValue < 0) to be true if the user failed to enter a valid value...
0

put an if statement inside your while loop like this

if(num <= 0){
   System.out.println("Enter a number greater than zero");
}
else{
   break;
}

Comments

0

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;
}

`

Comments

-1

using .isDigit() method then checking to see if that number is greater than 0 if it is a digit

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.