【问题标题】:parseInt vs isDigitparseInt 与 isDigit
【发布时间】:2016-09-07 01:52:30
【问题描述】:

如果参数是 0 到 255(包括 0 到 255)之间的整数的字符串表示形式,我需要我的代码返回 true,否则返回 false。

例如: 字符串“0”、“1”、“2” ....“254”、“255”是有效的。

填充字符串(例如“00000000153”)也有效。

isDigit 显然也可以,但我想知道这是否会更有益和/或这甚至可以与填充字符串一起使用?

public static boolean isValidElement(String token) {
    int foo = Integer.parseInt("token");
    if(foo >= 0 && foo <= 255)
        return true;
    else 
        return false;
    }

【问题讨论】:

  • 您的代码不起作用?
  • JavaScript 和 Java 是两种完全不同的语言。

标签: java parseint


【解决方案1】:

isDigit 不起作用,因为它需要一个字符作为输入,如果它是从 0 到 9 的数字,则返回 true。[参考:isDigit javadoc]

因为在您的情况下,您需要测试从 0 到 255 的所有数字的字符串表示,因此您必须使用 parseInt

此外,还可以通过捕获NumberFormatException 来检查传递的令牌是否为有效数字,并在它不是有效整数的情况下返回 false。

public static boolean isValidElement(String token) {
    try{
        int foo = Integer.parseInt(token);
        if(foo >= 0 && foo <= 255)
            return true;
        else 
            return false;
    } catch (NumberFormatException ex) {
        return false;
    }
}

【讨论】:

  • "catch (NumberFormatException ex)" 中的 catch 和 ex 是什么意思?你为什么用try打开?
  • trycatch 是 Java 关键字。如果parseInt 提供了无法解析为整数的输入(例如Integer.parseInt("randomText")),它将抛出NumberFormatException try-catch 是捕获该异常并执行正确操作的语法,即返回 false,因为输入不是有效元素(不是 0 到 255 之间的数字表示)。你可以在java official tutorial中阅读更多关于try-catch的信息
【解决方案2】:

你可以使用正则表达式:

return token.matches("1?\\d{1,2}|2[0-4]\\d|25[0-5]");

【讨论】:

    【解决方案3】:

    因此,如果字符串不是有效数字,则 Integer.parseInt 将抛出 NumberFormatException,请记住这一点。

    我会使用 commons-math3 库中的 NumberUtils.isDigit() 进行检查,然后使用 Integer.valueOf 这是一个高效的数字解析器。

    if (NumberUtils.isDigit(token)) {
        int foo = Integer.valueOf(token);
        return (foo >=0 && foo <=255);
    }
    

    【讨论】:

      【解决方案4】:

      Integer.parseInt 如果无法进行转换,则抛出 NumberFormatException。考虑到这一点,您可以使用此代码 sn-p。 不需要额外的依赖。

      public static boolean isValidElement(String token) {
          try {
              int value = Integer.parseInt(token);
              return value >= 0 && value <= 255;
          } catch(NumberFormatException e) {
              return false;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2013-10-02
        • 1970-01-01
        • 2012-01-06
        • 1970-01-01
        • 2016-10-12
        • 1970-01-01
        • 1970-01-01
        • 2015-02-01
        • 1970-01-01
        相关资源
        最近更新 更多