【发布时间】:2018-02-08 10:23:55
【问题描述】:
我编写了以下代码来确定用户输入的数据类型。
更新:删除了对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 是一项昂贵的操作。
有没有更好的方法来实现这一点?
【问题讨论】:
-
您是否尝试过,在哪里可以使用 instanceof?
-
这是错误的做法。您不必优化您编写的所有内容。尤其是不要过早
-
您似乎正在投射到
Stringwilly-nilly 没有赶上ClassCastException。如果你知道它肯定是一个字符串,为什么不把参数变成一个字符串呢? -
成功解析为
float并不意味着该数字不能是精度更高的double。解析为float只会丢弃字符串中存在的额外无法表示的精度。你最好总是解析为double。 -
@Jayanth 您应该先阅读其他答案,抱歉,
instanceOf无济于事。