0

I'm making a program where I want the user to input a value into a variable. After it is inputted I want to check the value type, but I don't know how. It looks a bit like this:

import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
int num1;
num1 = scanner.nextInt();

I want some way of checking the type of num1, so that I can make sure the user has inputted a usable value i.e. to make sure they haven't inputted a string such as "qwerty" into the integer variable, so that I can go on to catch the error if they have, rather than end up with a java.util.InputMismatchException. I've tried:

if(num1 instanceof java.lang.String)

but it doesn't fix the error and it doesn't work for integers either.

Any ideas on how to fix this?

Sam
  • 6,961
  • 15
  • 44
  • 63
killeREVO
  • 11
  • 1
  • 2
  • Obviously a value declared as `int` isn't a `String`. You're thinking about this backwards: *everything* comes in as a string. You're scanning an int; if you get the exception, it's not an int. That *is* the check if you do it like this. – Dave Newton Dec 08 '13 at 14:26
  • 1
    This [post](http://stackoverflow.com/questions/3059333/validating-input-using-java-util-scanner) should be helpful – Vikas V Dec 08 '13 at 14:26

2 Answers2

3
public boolean isInteger( String input ) {

  try {
    Integer.parseInt( input );
    return true;
   }
    catch( Exception e ) {
    return false;
   }
}

Do as the others mentioned and use scanner.next() to retrieve a string. Afterwards you can use the above code snippet to check if a string is an Integer.

For a double it looks pretty similiar:

boolean isDouble(String str) {

try {
    Double.parseDouble(str);
    return true;
  } catch (NumberFormatException e) {
    return false;
  }
}
Ben
  • 1,097
  • 5
  • 11
1

Java is a static typed language so scanner.nextInt(); will always return int.

If you want the return type to be String call scanner.next()

Patrick Favre
  • 29,166
  • 6
  • 96
  • 114
  • Adding to this: you can use `Integer.parseInt()` to check whether or not it can be represented as an integer. You can do this for every type you wish to check, but you'll still have the exceptions to work with. – Jeroen Vannevel Dec 08 '13 at 14:29