Figuring out whether a number is a Double in Java

JavaTypeof

Java Problem Overview


I'm a Java newbie. I'm trying to figure out whether a number is a Double with something like this:

if ( typeof ( items.elementAt(1) )== Double ) {
       sum.add( i, items.elementAt(1));
}

Would appreciate if someone could tell me how to rearrange the syntax to make this work properly.

Java Solutions


Solution 1 - Java

Try this:

if (items.elementAt(1) instanceof Double) {
   sum.add( i, items.elementAt(1));
}

Solution 2 - Java

Since this is the first question from Google I'll add the JavaScript style typeof alternative here as well:

myObject.getClass().getName() // String

Solution 3 - Java

Reflection is slower, but works for a situation when you want to know whether that is of type Dog or a Cat and not an instance of Animal. So you'd do something like:

if(null != items.elementAt(1) && items.elementAt(1).getClass().toString().equals("Cat"))
{
//do whatever with cat.. not any other instance of animal.. eg. hideClaws();
}

Not saying the answer above does not work, except the null checking part is necessary.

Another way to answer that is use generics and you are guaranteed to have Double as any element of items.

List<Double> items = new ArrayList<Double>();

Solution 4 - Java

Use regular expression to achieve this task. Please refer the below code.

public static void main(String[] args) {
    try {

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter your content: ");
        String data = reader.readLine();            
        boolean b1 = Pattern.matches("^\\d+$", data);
        boolean b2 = Pattern.matches("[0-9a-zA-Z([+-]?\\d*\\.+\\d*)]*", data); 
        boolean b3 = Pattern.matches("^([+-]?\\d*\\.+\\d*)$", data);
        if(b1) {
            System.out.println("It is integer.");
        } else if(b2) {
            System.out.println("It is String. ");
        } else if(b3) {
            System.out.println("It is Float. ");
        }           
    } catch (IOException ex) {
        Logger.getLogger(TypeOF.class.getName()).log(Level.SEVERE, null, ex);
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKerzinView Question on Stackoverflow
Solution 1 - JavaskiView Answer on Stackoverflow
Solution 2 - JavaRob FoxView Answer on Stackoverflow
Solution 3 - Javauser2537701View Answer on Stackoverflow
Solution 4 - JavakumarancView Answer on Stackoverflow