我在Core java中有一个问题.考虑具有名为age的属性的Employee类.
class Employee{
private int age;
public void setAge(int age);
}
Run Code Online (Sandbox Code Playgroud)
我的问题是我如何限制/阻止setAge(int age)方法使得它只接受正数并且它不应该允许负数,
Note: This has to be done without using client side validation.how do i achieve it using Java/server side Validation only.The validation for age attribute should be handled such that no exception is thrown
您只需在方法中验证用户的输入:
public void setAge(int age) {
if (age < 0)
throw new IllegalArgumentException("Age cannot be negative.");
// setter logic
}
Run Code Online (Sandbox Code Playgroud)
如果您不能抛出异常,那么您可能想尝试:
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;
}
Run Code Online (Sandbox Code Playgroud)
您可以返回该值是否有效.