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?

3 Answers3

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
}
Column-E
  • 96
  • 4
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

}

...
licklake
  • 236
  • 4
  • 15
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?

Community
  • 1
  • 1
Danyal Sandeelo
  • 12,196
  • 10
  • 47
  • 78