[英]how to check primitive data type of any value in java
I have a file containing list of values which may be just a string or an integer. 我有一个包含值列表的文件,该值列表可能只是字符串或整数。
bhushan 21
kedar 20
When i read values in a string array i also want to perform some arithmetic operations if the data that i have is an integer or double. 当我读取字符串数组中的值时,如果我拥有的数据是整数或双精度数,我也想执行一些算术运算。 How do i check whether the data that i have is an integer, double or a string?
如何检查我拥有的数据是整数,双精度还是字符串? I am currently storing all values in a string array using split function and whenever i want to take average of all numbers i convert the numbers that i am sure of to integers or double and then perform arithmetic operations.
我目前正在使用拆分功能将所有值存储在字符串数组中,每当我想取所有数字的平均值时,我会将我确定的数字转换为整数或双精度数,然后执行算术运算。 I want to write a method that will tell me what exactly is the type of that value.
我想写一个方法,告诉我该值的类型到底是什么。
Using a regular expression should be the most efficient way. 使用正则表达式应该是最有效的方法。 Other expressions can be used to further look for floating point numbers, etc.
其他表达式可用于进一步查找浮点数等。
String input = "12345";
java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(".*[^0-9].*");
if( pattern.matcher(input).matches() )
System.out.println("Its a number");
else
System.out.println("Its not a number");
You can also use the Integer.parseInt()
or Double.parseDouble()
methods, however, they will throw a NumberFormatException
if the input does not conform. 您也可以使用
Integer.parseInt()
或Double.parseDouble()
方法,但是,如果输入不符合要求,它们将抛出NumberFormatException
。
You can do that with simple function; 您可以通过简单的功能来实现;
public static boolean isValueInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;//For example "bhushan"
}
return true;// For example "21"
}
It will throw NumberFormatException
if it is a String
如果它是一个
String
,它将抛出NumberFormatException
You can try to cast it from string to int. 您可以尝试将其从字符串转换为整数。
try{
int result = Integer.parseInt(stringValue);
} catch (NumberFormatException nfe) {
}
You usually would use something like regular expression for that. 通常,您会使用诸如正则表达式之类的东西。 eg
例如
String number = "daaaa";
Pattern digitPattern = Pattern.compile("\\d{6}");
if (digitPattern.matcher(number).matches()) {
System.out.println(number + " is a number.");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.