作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个相同原始类型的字符串数组(不知道是什么)。我需要将其转换为相应的类型。如果我传递一个字符串并获取数据的原始类型(如果该字符串中有的话),有什么办法吗?考虑字符串应该具有原始类型或者它被视为字符串
对于例如
"5.2" - double
"5" - int (most related)
"s" - char
因此,如果它是 double 的,我可以使用 Double.parseDouble
进行解析
最佳答案
不,那是不可能的。例如这个输入:
5
我们唯一知道的是,它可能不是 boolean 值。
你当然也可以尝试像这样解析你的字符串:
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();
}
对于给定的例子,它输出:
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
关于Java : Is there a way to know the type of primitive data in a string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35651567/
我是一名优秀的程序员,十分优秀!