如果金额不是整数或浮点数,则下面是抛出异常的方法 但是当我强行传递字符串时它不起作用,因为在字符串的情况下它应该抛出异常并使有效为false但它仍然返回有效为真,请告知我的表达式下面的错误
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;
}
答案 0 :(得分:3)
你不是想把它转换成任何地方,所以不会抛出任何异常。就这样做......
private boolean isAmount(String amount) {
return amount.matches("[-+]?[0-9]*\\.?[0-9]+"));
}
答案 1 :(得分: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;
}
答案 2 :(得分: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;
}