You just need to check the user input in the method:
public void setAge(int age) {
if (age < 0)
throw new IllegalArgumentException("Age cannot be negative.");
}
If you cannot throw an exception, you can try:
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;
}
You can return whether the value was valid.
source
share