gpt4 book ai didi

Java : Is there a way to know the type of primitive data in a string

转载 作者:行者123 更新时间:2023-12-03 22:54:06 24 4
gpt4 key购买 nike

我有一个相同原始类型的字符串数组(不知道是什么)。我需要将其转换为相应的类型。如果我传递一个字符串并获取数据的原始类型(如果该字符串中有的话),有什么办法吗?考虑字符串应该具有原始类型或者它被视为字符串

对于例如

"5.2" - double
"5" - int (most related)
"s" - char

因此,如果它是 double 的,我可以使用 Double.parseDouble 进行解析

最佳答案

不,那是不可能的。例如这个输入:

5
  • 这可能是一个int
  • 但也可以是字节
  • 也可以是floatdouble
  • 它甚至可以是一个char

我们唯一知道的是,它可能不是 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com