Integer vs. String decision making in Java

integer, java, string

Solution

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

Problem

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.

Original source