如果有一个包含数字字符串的字符串变量,是否有任何函数可以识别该值是否可以转换为int,double或其他任何东西?我需要java中的函数名称
答案 0 :(得分:1)
String sent3 = "123";
System.out.println(sent3.matches("[0-9]+"));
System.out.println(sent3.matches("[0-9]+\\.[0-9]+"));// for double
输出: - true
如果输出为true
,则可以将其转换为int。
答案 1 :(得分:1)
String test = "1234";
System.out.println(test.matches("-?\\d+"));
test = "-0.98";
System.out.println(test.matches("-?\\d+\\.\\d+"));
第一个匹配(即打印为true)任何整数(不是int
,整数),前面带有可选的-
符号。第二个匹配任何double
值与可选的-
符号,在所需小数点之前至少有一个数字,并且至少在小数点后面的数字上。
此外,函数名称为String.matches
,它使用正则表达式。
答案 2 :(得分:1)
我的解决方案涉及尝试将字符串解析为各种类型,然后查找Java可能抛出的异常。这可能是一个效率低下的解决方案,但代码相对较短。
public static Object convert(String tmp)
{
Object i;
try {
i = Integer.parseInt(tmp);
} catch (Exception e) {
try {
i = Double.parseDouble(tmp);
} catch (Exception p) {
return tmp; // a number format exception was thrown when trying to parse as an integer and as a double, so it can only be a string
}
return i; // a number format exception was thrown when trying to parse an integer, but none was thrown when trying to parse as a double, so it is a double
}
return i; // no numberformatexception was thrown so it is an integer
}
然后,您可以将此功能与以下代码行一起使用:
String tmp = "3"; // or "India" or "3.14"
Object tmp2 = convert(tmp);
System.out.println(tmp2.getClass().getName());
您可以将函数转换为内联代码,以测试它是否为整数,例如:
String tmp = "3";
Object i = tmp;
try {
i = Integer.parseInt(tmp);
} catch (Exception e) {
// do nothing
}
我有点草率,试图捕捉正常的异常,这是相当通用的 - 我建议你使用“NumberFormatException”。