Home > Software design >  How to create a validation for only certain ages java
How to create a validation for only certain ages java

Time:10-22

I need to write a validation that validates a persons age. The age can only be 20, 30, or 40. When I create the below method and try and create a person object that is age 30, i get the illegal argument exception. Any ideas why?

  private static void validateAge(final int age) {

    if (age != 20 || age != 30 || age != 40 ) {
        throw new IllegalArgumentException("invalid age "   age);
    }

}

CodePudding user response:

So the only legal values are 20, 30, or 40.
This means: age == 20 || age == 30 || age == 40 which negated is age != 20 && age != 30 && age != 40.

CodePudding user response:

public class Test {
    
    public static void main(String args[]){
        
        int age = 20;
        
        boolean isValid = isValidAge(age);
        
        if(isValid)
            System.out.println("Entered Age is Valid.");
        else
            System.out.println("Entered Age is InValid.");
    }
    
    private static boolean isValidAge(final int age){
        if(age != 20 && age != 30 && age != 40)
            return false;
        else
            return true;
    }
}
  • Related