Reputation: 11
This is the program that I have written & I want to solve this in some other way. I don't want to use the try-catch statement.
I have researched about other ways but it was not clearly explained.
import java.io.*;
import java.util.*;
public class TPJava {
public static void main(String args[]) throws Exception {
Scanner scan = new Scanner(System.in);
try {
int int_var = scan.nextInt();
System.out.println("It is an Integer.");
}
catch (InputMismatchException e)
{
try
{
String str_var = scan.next();
System.out.println("It is a String");
}
catch (InputMismatchException ie)
{
try
{
Float f = scan.nextFloat();
System.out.println("It is Float");
}
catch (InputMismatchException ime)
{
System.out.println("Wrong Input.");
}
}
}
}
}
Upvotes: 0
Views: 51
Reputation: 81
if (XXX instanceof int)
{
System.out.println("It is an integer.");
}
else if (XXX instanceof String)
{
System.out.println("It is a string.");
}
....
(and so on)
EDIT: found a solution that should work for exactly your code.
Scanner scan= new Scanner(System.in);
if(scan.hasNextInt())
{
System.out.println("It is an integer.");
}
else if (scan.hasNextFloat())
{
System.out.println("It is a Float.");
}
....
else
{
System.out.println("It is a String.");
}
this checks if the next variable can be interpreted as a integer/float/ etc..... i think there is none for "String" so i just used the "else" statement there
BUT: you have to user scan.next() or nextInt or something like that afterwards, else it will continuesly use the same input over and over again (i assume)
Upvotes: 1