2

如果金额不是整数或浮点数,以下是抛出异常的方法,但是当我强制传递字符串时它不起作用,因为在字符串的情况下它应该抛出异常并使有效为假,但它仍然返回有效为真的请告诉我下面的表达有什么问题

private boolean isAmount(String amount) {
    boolean isValid = true;
    try {
        if (amount.matches("[-+]?[0-9]*\\.?[0-9]+"))  {
            return isValid;     
        }
    }
    catch (NumberFormatException e) {
        isValid = false;
    }
    return isValid;
}
4

3 回答 3

3

您不会尝试在任何地方进行转换,因此不会引发异常。就这样做...

private boolean isAmount(String amount) {
    return amount.matches("[-+]?[0-9]*\\.?[0-9]+"));
}
于 2013-05-06T08:46:21.473 回答
3

您的正则表达式工作得很好,它周围的逻辑不起作用:

这将起作用:

private boolean isAmount(String amount) {
  if(amount == null) return false;
  if (amount.matches("[-+]?[0-9]*\\.?[0-9]+")) return true;
  return false;
}

或者是这样的:

private boolean isAmount(String amount) {
  boolean ret = true;
  try {
    double val = Double.parseDouble(amount);
  } catch (NumberFormatException e) {
    ret = false;
  }
  return ret;
}
于 2013-05-06T08:47:04.483 回答
1
   // Try this one to check the output - running fine.... as per your needs

    private boolean isAmount(String amount) {
    boolean isValid = true;
    try {
           if (amount.matches("[-+]?[0-9]*\\.?[0-9]+"))  {
           isValid= true; 
}   
else
{
 isValid = false;
}

}catch (NumberFormatException e) {
    isValid = false;
    }
    return isValid;
    }
于 2013-05-06T09:15:36.653 回答