Determine user input data-type dynamically in JAVA

Kainix :

I've written the following code to determine the data-type of input entered by the user.

Update: Removed parsing into Float since a Double value can also be parsed into Float at cost of some precision as mentioned by @DodgyCodeException

import java.util.Scanner;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Main {

    public static void main(String[] args) {
        Scanner src = new Scanner(System.in);
        String input;
        System.out.println("Enter input:");
        input = src.nextLine();
        System.out.println("You entered:" + getDataType(input));
    }

    private static String getDataType(Object input) {
        try {
            JSONObject obj = new JSONObject((String) input);
            return "JSONObject";
        } catch (JSONException ex) {
            try {
                JSONArray array = new JSONArray(input);
                return "JSONArray";
            } catch (JSONException ex0) {
                try {    
                    Integer inti = Integer.parseInt((String) input);
                    return "Integer";
                } catch (NumberFormatException ex1) {
                    try {                          
                            Double dub = Double.parseDouble((String) input);
                            return "Double";
                        } catch (NumberFormatException ex3) {
                            return "String";
                        }
                    }
                }
            }
        }
    }
}

I've to run this repeatedly hundreds of time and I've read catching Exception is an expensive operation.
Is there any better way to achieve this?

Henrik Aasted Sørensen :

My approach would be to let the framework do its thing, and use it to parse the input a generic way:

Object obj = new org.json.JSONTokener(input).nextValue();
if (obj instanceof JSONArray)
    return "JSONArray";

if (obj instanceof JSONObject)
    return "JSONObject";

if (obj instanceof Integer)
    return "Integer"
...

Perhaps use a switch statement or a Map instead of a long list of if constructs. And catch JSONException for input that is not valid JSON.

Could perhaps be simplified to return obj.getClass() or obj.getClass().getSimpleName() for almost identical functionality to what you have now.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=439772&siteId=1