Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent negative numbers for age without using client side validation

Tags:

java

I have an issue in Java. Consider the Employee class having an attribute called age.

class Employee{           
      private int age;     
      public void setAge(int age);     
}

How do I restrict/prevent the setAge(int age) method such that it accepts only positive numbers and it should not allow negative numbers,

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.

like image 902
Deepak Avatar asked Mar 22 '26 16:03

Deepak


1 Answers

You simply have to validate the input from the user in the method:

public void setAge(int age) {
    if (age < 0) 
        throw new IllegalArgumentException("Age cannot be negative.");
    // setter logic
}

If you cannot throw an exception then you might wanna 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 or not the value was valid.

like image 144
jjnguy Avatar answered Mar 25 '26 06:03

jjnguy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!