-3

I have been using Scanner and System.in recently, but I am not able to find a code that can judge whether the input is a String or an integer and then treat it accordingly. Does anonye know a way?

  • 2
    possible duplicate of [How to check if a String is a numeric type in Java](http://stackoverflow.com/questions/1102891/how-to-check-if-a-string-is-a-numeric-type-in-java) – Nick L. Dec 18 '14 at 14:26

2 Answers2

2

Use Scanner.next() to get the input String then test with Integer.parseInt(String) if it's integer or not. try this code:

Scanner scanner = new Scanner(System.in);
if(scanner.hasNext())
{
        String s = scanner.next();
        try
        {
            int number = Integer.parseInt(s);
            System.out.println("Your input is an integer.");
        }
        catch(NumberFormatException e)
        {
            System.out.println("Your input is a String.");
        }
}
Naruto Biju Mode
  • 1,871
  • 3
  • 13
  • 27
0
try{ 
  Integer.parseInt(input);
}catch(NumberFormatException e){
    System.out.printerr("Not an integer: " + input);
}
agad
  • 2,102
  • 1
  • 18
  • 30