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?
Asked
Active
Viewed 42 times
-3
-
2possible 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 Louloudakis Dec 18 '14 at 14:26
2 Answers
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
- 2,011
- 3
- 15
- 28
0
try{
Integer.parseInt(input);
}catch(NumberFormatException e){
System.out.printerr("Not an integer: " + input);
}

agad
- 2,192
- 1
- 20
- 32