我有一个相同原始类型的字符串数组(不知道是什么).我需要将其转换为相应的类型.有没有办法,如果我传递一个字符串,并获得该字符串中的数据的原始类型.考虑字符串应该具有基本类型或者它被视为String
例如
"5.2" - double
"5" - int (most related)
"s" - char
Run Code Online (Sandbox Code Playgroud)
所以,如果它是双,我可以解析使用 Double.parseDouble
不,那是不可能的.例如这个输入:
5
Run Code Online (Sandbox Code Playgroud)
我们唯一知道的是,它可能不是布尔值.
您当然也可以尝试解析您的字符串,如下所示:
public static void main(String[] args) {
checkType("5.2");
checkType("5");
checkType("s");
}
protected static void checkType(String input) {
System.out.println(input);
try {
byte result = Byte.parseByte(input);
System.out.println("could be interpreted as byte "+result);
} catch (NumberFormatException e) {
System.out.println("not an byte");
}
try {
short result = Short.parseShort(input);
System.out.println("could be interpreted as short "+result);
} catch (NumberFormatException e) {
System.out.println("not an short");
}
try {
int result = Integer.parseInt(input);
System.out.println("could be interpreted as int "+result);
} catch (NumberFormatException e) {
System.out.println("not an int");
}
try {
long result = Long.parseLong(input);
System.out.println("could be interpreted as long "+result);
} catch (NumberFormatException e) {
System.out.println("not an long");
}
try {
float result = Float.parseFloat(input);
System.out.println("could be interpreted as float "+result);
} catch (NumberFormatException e) {
System.out.println("not an float");
}
try {
double result = Double.parseDouble(input);
System.out.println("could be interpreted as double "+result);
} catch (NumberFormatException e) {
System.out.println("not an double");
}
try {
boolean result = Boolean.parseBoolean(input);
System.out.println("could be interpreted as boolean "+result);
} catch (NumberFormatException e) {
System.out.println("not a boolean");
}
if (input.length() == 1) {
System.out.println("could be interpreted as character "+input);
} else {
System.out.println("not a character");
}
System.out.println();
}
Run Code Online (Sandbox Code Playgroud)
对于给定的示例,它输出:
5.2
not an byte
not an short
not an int
not an long
could be interpreted as float 5.2
could be interpreted as double 5.2
could be interpreted as boolean false
not a character
5
could be interpreted as byte 5
could be interpreted as short 5
could be interpreted as int 5
could be interpreted as long 5
could be interpreted as float 5.0
could be interpreted as double 5.0
could be interpreted as boolean false
could be interpreted as character 5
s
not an byte
not an short
not an int
not an long
not an float
not an double
could be interpreted as boolean false
could be interpreted as character s
Run Code Online (Sandbox Code Playgroud)