在JAVA中动态确定用户输入数据类型 [英] Determine user input data-type dynamically in JAVA

查看:117
本文介绍了在JAVA中动态确定用户输入数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了以下代码来确定用户输入的输入的数据类型.

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

更新:删除了对Float的解析,因为Double值也可以按@DodgyCodeException

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

我必须重复运行数百次,而且我已经阅读捕获Exception是一项昂贵的操作.
有没有更好的方法来实现这一目标?

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?

推荐答案

我的方法是让框架执行其工作,并使用它来解析输入的通用方法:

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"
...

也许使用switch语句或Map代替一长串的if构造.并捕获JSONException来输入无效的JSON.

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.

也许可以简化为返回obj.getClass()obj.getClass().getSimpleName()来返回与您现在拥有的功能几乎相同的功能.

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

这篇关于在JAVA中动态确定用户输入数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆