【问题标题】:Java method which check is it a number检查是否为数字的 Java 方法
【发布时间】:2018-06-24 16:35:20
【问题描述】:

我写了一个方法,它接受一个字符串,如果它是一个有效的单个整数或浮点数,则返回 true,否则返回 false。

我的代码:

public static boolean isDigit(String s)
    {
        boolean b;
        try
        {
            Integer.parseInt(s);
            b = true;
        }
        catch (NumberFormatException e)
        {
            b = false;
        }

        try
        {
            Double.parseDouble(s);
            b = true;
        }
        catch (NumberFormatException e)
        {
            b = false;
        }

        return b;
    }

我相信有更好的写法。谢谢

【问题讨论】:

标签: java numbers int double


【解决方案1】:

你不需要检查它是否是int,因为int数字也可以解析为double。可以简化为:

public static boolean isDigit(String s)
{
    boolean b;

    try
    {
        Double.parseDouble(s);
        b = true;
    }
    catch (NumberFormatException e)
    {
        b = false;
    }

    return b;
}

【讨论】:

  • 可以通过直接删除 breturning truefalse 来进一步简化。
【解决方案2】:

您也可以使用正则表达式来执行此操作。

 public static boolean isDigit(String s){
    String regex = "[0-9]*\\.?[0-9]*";
    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(s);
    boolean b = m.matches();
    return b;
  }

【讨论】:

    【解决方案3】:

    最轻的解决方案是这个,也是为了代码可读性:

    public boolean isDigit(String str) {
         try {
              Integer.parseInt(str)
              return true;
         } catch (NumberFormatException: e) { return false }
    }
    

    【讨论】:

      【解决方案4】:

      使用 Apache Commons StringUtils.isNumeric() 检查 String 是否为有效数字

      例子:-

      StringUtils.isNumeric("123") = true StringUtils.isNumeric(null) = false StringUtils.isNumeric("") = false StringUtils.isNumeric(" ") = false

      【讨论】:

        【解决方案5】:

        你可以这样做:

         return s.matches("[+-]?\\d+(\\.\\d+)?");
        

        如果“。”是小数的分隔符

        【讨论】:

        • 负数/一元正数呢?
        • 答案已编辑,现在也适用于负数,谢谢@Reimeus
        猜你喜欢
        • 1970-01-01
        • 2018-05-04
        • 2012-01-16
        • 1970-01-01
        • 1970-01-01
        • 2014-07-04
        • 1970-01-01
        • 2010-12-20
        相关资源
        最近更新 更多