如何确定Java中的数字数据类型?

时间:2018-06-21 10:08:22

标签: java types int double metadatatype

我想知道用户输入的是char还是int,因此根据数据类型采取不同的操作方式。

2 个答案:

答案 0 :(得分:1)

您可以将行读为String,然后使用正则表达式检查字符串。例如,如果您正在从stdin

阅读
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

String inputString = bufferedReader.readLine();

String doubleRegex = "[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?";
String integerRegex = "[-+]?[0-9]+";

if (inputString.matches(integerRegex)) {
    System.out.println("integer");
} else
if (inputString.matches(doubleRegex)) {
    System.out.println("double");
} else {
    // Error inputted string can't be parsed
}

答案 1 :(得分:0)

尝试java std解析器:

public static void main(String[] args) throws IOException {

    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
    String inputString = bufferedReader.readLine();
    Integer integerValue = getIntegerValueOf(inputString);
    if (integerValue == null) {
        Double doubleValue = getDoubleValueOf(inputString);
        if (doubleValue == null) {
            System.out.println("I don't know");
        } else {
            System.out.println("Congratulation, it's a double : " + doubleValue);
        }
    } else {
        System.out.println("Congratulation, it's a integer : " + integerValue);
    }

}

private static Integer getIntegerValueOf(String inputString) {
    try {
        return Integer.parseInt(inputString);
    } catch (NumberFormatException e) {
        return null;
    }
}

private static Double getDoubleValueOf(String inputString) {
    try {
        return Double.parseDouble(inputString);
    } catch (NumberFormatException e) {
        return null;
    }
}