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?
Determine wether input is an int or a string
56 Views Asked by Fredrik Arentz At
2
There are 2 best solutions below
0

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.");
}
}