Home > Software design >  Two methods look like they are doing the same thing but give different output. Why?
Two methods look like they are doing the same thing but give different output. Why?

Time:02-06

Inputs:

-6
1
-5 

Method 1:

public void setGoalkeepingSkill(int goalkeepingSkill) {
    if (goalkeepingSkill > 5 && goalkeepingSkill < 1) {
        System.out.println("invalid skill value goalkeeping");
        this.goalkeepingSkill = 1;
    } else {
        this.goalkeepingSkill = goalkeepingSkill; 
        System.out.println("Goalkeeping Skill has been set");
    }
}

Output:

Goalkeeping Skill has been set
Goalkeeping Skill has been set
Goalkeeping Skill has been set

Method 2:

public void setGoalkeepingSkill(int goalkeepingSkill) {

    if(goalkeepingSkill<=5 && goalkeepingSkill>=1){
        this.goalkeepingSkill = goalkeepingSkill;
        System.out.println("Goalkeeping Skill has been set");
    }else{
        this.goalkeepingSkill=1;
        System.out.println("invalid skill value goalkeeping");
    }
}

Output:

invalid skill value goalkeeping
Goalkeeping Skill has been set
invalid skill value goalkeeping

CodePudding user response:

In the first method, the conditon goalkeepingSkill > 5 && goalkeepingSkill < 1 is always false. No number can be both greater than 5 and less than 1. If you want to inverse the condition of the second method, you need to use the || logical operator instead of &&:

public void setGoalkeepingSkill(int goalkeepingSkill) {
    if (goalkeepingSkill > 5 || goalkeepingSkill < 1) {
        // Here -------------^
        System.out.println("invalid skill value goalkeeping");
        this.goalkeepingSkill = 1;
    } else {
        this.goalkeepingSkill = goalkeepingSkill; 
        System.out.println("Goalkeeping Skill has been set");
    }
}
  • Related