java 中输入值,在JAVA中动态确定用户输入数据类型

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?

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值