Reputation:
I'm working on a program where user input is an array of mixed Strings and Integers. For Example:
dog 10 23 cat frog 22 elephant
I'm supposed to sort this array without changing the type of each index. So the output will be;
cat 10 22 dog elephant 23 frog
After reading the line from the console, I'm using a string tokenizer to go through each element. After that I'm trying to parseInt and if it throws an exception, I'm assuming that it is a string, otherwise it is an Integer. Is there a better way to figure out if a token is numerical or not?
Thank you.
Upvotes: 4
Views: 389
Reputation: 2883
You can for example use 'StringUtils.isNumeric' to detect if a string is numerical
http://commons.apache.org/lang/api-2.3/org/apache/commons/lang/StringUtils.html
The drawback is that you have to include a library.
Upvotes: 0
Reputation: 1475
Relying on exceptions for program logic is considered poor practice because exceptions are slow. Instead, you can use regular expressions.
Matcher numericalMatcher = Pattern.compile("^-?\\d+$").matcher(token);
if( numericalMatcher.matches() ) {
// Token is a number
} else {
// Token is not a number
}
See http://docs.oracle.com/javase/1.6.0/docs/api/java/util/regex/Pattern.html and http://docs.oracle.com/javase/1.6.0/docs/api/java/util/regex/Matcher.html
Upvotes: 6
Reputation: 7807
Using parseInt
is not a bad idea.
Alternatively you can use a regular expression but I believe your choice is more practical and simple.
Upvotes: 3