我编写了以下代码来确定用户输入的数据类型。
更新:删除了解析为 Float
,因为 Double
值也可以解析为 Float
,代价为@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
是一项代价高昂的操作。
有没有更好的方法来实现这一点?
最佳答案
我的方法是让框架做它的事情,并用它以一种通用的方式解析输入:
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
结构。并为无效 JSON 的输入捕获 JSONException
。
也许可以简化为返回 obj.getClass()
或 obj.getClass().getSimpleName()
以获得与您现在拥有的几乎相同的功能。
关于java - 在 JAVA 中动态确定用户输入的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48683126/