0

I'm currently working on a program that accepts integer values at one point (using Scanner method nextInt). Of course, if you type "one" instead of "1", the program crashes. I'm trying to get it instead to just to say that it was an invalid input and to try again if it isn't an integer, and continue if the value is an integer. So far I'm using the Scanner method hasNextInt, which determines if the value is an integer and returns a boolean value, but the part I'm having trouble with is continuing if an integer value was inputted. So is it possible to continue the program with the inputted value without having to ask for it again?

6
  • Please share sample input and output. Commented Apr 19, 2016 at 13:07
  • 3
    Please post your code... Commented Apr 19, 2016 at 13:07
  • I would read a string with nextLine, then try catch to parseInt within a while loop, but can you please show your code? There is an 'edit' link under the text of the question. Commented Apr 19, 2016 at 13:08
  • 1
    read a String,parse to int, catch Exception. Commented Apr 19, 2016 at 13:08
  • 1
    Why is if (scanner.hasNextInt()) { i = scanner.nextInt();} not acceptable for your case? Commented Apr 19, 2016 at 13:13

3 Answers 3

1

Since you are using java.util.Scanner, there is a method

scanner.hasNextInt();

That checks if there is an integer input.

int value = 0;

if(scanner.hasNextInt()) {
    value = scanner.nextInt();
} else {
    // handle bad input
}
Sign up to request clarification or add additional context in comments.

Comments

0

You could try:

...

Scanner in = new Scanner(System.in);

try {

  String intS = in.nextLine();
  int intI = Integer.parseInt(intS);

} catch (Exception e) {

   System.out.println("Error, no Int!")
   //or something

}

...

Comments

0
if (x == (int)x)
{
   // Number is integer
}

and try that too

Object x = someApi();

if (x instanceof Integer) 

How can I check if a value is of type Integer? and How to check if the value is integer in java?

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.