java 两个方法看起来好像在做同样的事情,但是给予不同,为什么?

xpcnnkqh  于 2023-02-07  发布在  Java
关注(0)|答案(1)|浏览(91)

输入:

-6
1
-5

方法一:

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");
    }
}

输出:

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

方法二:

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");
    }
}

输出:

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

y4ekin9u1#

在第一种方法中,条件goalkeepingSkill > 5 && goalkeepingSkill < 1总是false,不能同时大于5和小于1,如果要反转第二种方法的条件,需要使用||逻辑运算符,而不是&&

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");
    }
}

相关问题