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.
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
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.");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.