我在 Core java 中遇到问题。 考虑具有名为 age 的属性的 Employee 类。
class Employee{
private int age;
public void setAge(int age);
}
我的问题是如何限制/阻止 setAge(int age) 方法,使其只接受正数而不允许负数,
注意:这必须在不使用客户端验证的情况下完成。我如何仅使用 Java/服务器端验证来实现它。应该处理年龄属性的验证,以便不抛出异常
最佳答案
您只需验证方法中用户的输入:
public void setAge(int age) {
if (age < 0)
throw new IllegalArgumentException("Age cannot be negative.");
// setter logic
}
如果你不能抛出异常,那么你可能想尝试:
public boolean setAge(int ageP) {
// if our age param is negative, set age to 0
if (ageP < 0)
this.age = 0
else
this.age = ageP;
// return true if value was good (greater than 1)
// and false if the value was bad
return ageP >= 0;
}
您可以返回该值是否有效。
关于java - 在不使用客户端验证的情况下防止年龄的负数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4899562/