0

我通过 pojo 的 getter 方法获取对象中的金额,但是金额 getter 方法的返回类型在 pojo 中设置为字符串,如下所示

//setting need to be done in pojo
private String amount;

    public String getAmount() {
        return amount;
    }

让我们在下面说有对象 h 我正在检索它

h.getAmount()

现在我需要开发一个验证器来验证该金额应该是整数类型,如果不是,那么它将抛出异常请告知我如何开发一个单独的方法来检查金额是否为整数和在此基础上会返回 true 或 false ,如下图

// Validate the amount is in integer
private boolean isValidAmount (String Amount) {
    boolean valid = false;
//code to check whether the Amount is integer or not, if integer then
//return true else return false
}

我已经更新了帖子,因为它引发了数字格式异常,请告知

4

4 回答 4

3

您可以尝试解析它,如果解析成功则返回 true。

try {
    Integer.parseInt(amount);
    return true;
} catch (NumberFormatException e) {
    return false;
}

编辑

我刚刚重新阅读了这个问题,并注意到如果无法解析字符串,您似乎唯一想要对这个真/假值做的事情就是可能引发异常。在这种情况下,您可以摆脱那个布尔中间人:

try {
    Integer.parseInt(amount);
} catch (NumberFormatException e) {
    throw new MyWhateverException(amount);
}
于 2013-05-06T06:08:43.217 回答
0

你为什么不尝试使用它,如果它失败,它Integer.parseInt(someString); 会抛出一个。NumberFormatException

于 2013-05-06T06:08:24.933 回答
0
boolean flag = false;
try{
  int amount = Integer.parseInt(amount);
  flag = true;
} catch(NumberFormatException e) {
flag = flase;
}

return flag;

如果金额是整数格式,那么它不会通过任何异常,否则它将通过 NumberFormatException。

在此处获取 parseInt() 的更多详细信息。

于 2013-05-06T06:12:21.233 回答
0
public boolean isValidAmount (Object h){
   try {
       Integer.parseInt(h.amount);
       return true;
    } catch (NumberFormatException e) {
      return false;
    }
}

试试这个,可能对你有用

于 2013-05-06T06:14:02.167 回答