【问题标题】:Check input for number检查输入的数字
【发布时间】:2012-11-27 21:01:14
【问题描述】:

我是 Java 新手。我创建此代码是为了检查输入字段中的字符串或数字。

try {
    int x = Integer.parseInt(value.toString());
} catch (NumberFormatException nFE) {
    // If this is a string send error message
    throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
            "  " + findValue + " must be number!", null));
}

如何创建相同的号码检查但只使用 if(){} 而不使用 try-catch?

【问题讨论】:

  • 你为什么不想要try/catch?你已经在使用异常了。

标签: java exception-handling int validation


【解决方案1】:

您可以使用patternString#matches 方法:-

String str = "6";

if (str.matches("[-]?\\d+")) {
    int x = Integer.parseInt(str);
}

"[-]?\\d+" 模式将匹配digits 的任何序列,前面是可选的- 符号。

"\\d+" 表示匹配一位或多位数字。

【讨论】:

  • +1 我总是试图将其解析为数字。这更优雅!
  • @RNJ.. 如果是integers,是的,它非常优雅。
  • 整洁,但为什么允许加号? "+6" 会抛出异常。
  • @whiskeyspider.. 哦,非常感谢。会编辑。没注意到。 :)
【解决方案2】:

如果您真的不想显式捕获异常,那么您最好创建一个辅助方法。

例如。

public class ValidatorUtils {

    public static int parseInt(String value) {
        try {
            return Integer.parseInt(value);
        } catch (NumberFormatException e) {
            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
            "  " + findValue + " must be number!", null));
        }
    }
}

public static void main(String[] args) {

    int someNumber = ValidatorUtils.parseInt("2");
    int anotherNumber = ValidatorUtils.parseInt("nope");

}

这样您甚至不需要使用 if 语句,而且您的代码不必解析整数两次。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-13
    • 1970-01-01
    • 1970-01-01
    • 2011-07-13
    • 2015-02-08
    • 2013-07-25
    • 1970-01-01
    相关资源
    最近更新 更多