如何编码“如果输入!=一个数字,然后......”

时间:2011-10-26 01:44:12

标签: java string numbers

好吧,我正试图找出这件事。你会如何编写这样的代码(在Javglish中):

if(input != a number)
{
    do something
}

我该怎么编码?

1 个答案:

答案 0 :(得分:3)

来自http://rosettacode.org/wiki/Determine_if_a_string_is_numeric#Java

(链接中的优化程度较差,更好的例子,如RegEx)

public boolean isNumeric(String input) {
  try {
    Integer.parseInt(input);
    return true;
  }
  catch (NumberFormatException e) {
    // s is not numeric
    return false;
  }

为未来的观众编辑:前面提到的RegEx方法更优雅,但如果您不熟悉正则表达式,则更难以理解:

public static boolean isNumeric(String inputData) {
  return inputData.matches("[-+]?\\d+(\\.\\d+)?");
}