4

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.

4

3 回答 3

6

依赖程序逻辑的异常被认为是不好的做法,因为异常很慢。相反,您可以使用正则表达式。

Matcher numericalMatcher = Pattern.compile("^-?\\d+$").matcher(token);
if( numericalMatcher.matches() ) {
   // Token is a number
} else {
   // Token is not a number
}

请参阅http://docs.oracle.com/javase/1.6.0/docs/api/java/util/regex/Pattern.htmlhttp://docs.oracle.com/javase/1.6.0/docs/api /java/util/regex/Matcher.html

于 2012-04-07T07:36:09.937 回答
3

使用parseInt不是一个坏主意。

或者,您可以使用正则表达式,但我相信您的选择更加实用和简单。

于 2012-04-07T07:34:29.347 回答
0

例如,您可以使用“StringUtils.isNumeric”来检测字符串是否为数字

http://commons.apache.org/lang/api-2.3/org/apache/commons/lang/StringUtils.html

缺点是您必须包含一个库。

于 2012-04-07T08:48:19.417 回答