而循环布尔混淆

时间:2017-06-13 13:38:34

标签: java while-loop

为什么我的布尔值在while循环后被设置为false。我已经放置了印刷语句和" if"设置t = false的while循环中的条件;永远不会受到打击为什么当我在for和while循环之间打印时,t = false; ?

public void addStudents(Student student){
    System.out.println("in addStudents");
    boolean t = true;
    int counter = 0;
    while ( t = true && counter < students.length ){
        // System.out.println("while");
        if (students[counter].equals(student)) {
            // System.out.println("ppppppppppppppppppppppp");
            t = false;
            counter ++;
            // System.out.println("never");
        } else {
            counter++;
        }
    }
    if (t == true) {
        if (students[students.length - 1] != null){
            // System.out.println("xxxxxxxxxxxx");
            Student[] newstudentsarray = new Student[students.length + 1];
            for (int i = 0; i < students.length; i++){
                newstudentsarray[i] = students[i];
            }
            students = newstudentsarray;
            students[students.length - 1] = student;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

问题在于Java Operator Precedence,其中运算符&&的优先级高于=

因此语句t = true && counter < students.length被合并到t = (true && counter < students.length)中,而t在循环结束时总是设置为false。

您可能想写t == true && counter < students.length,但输入错误==

这就是为什么写“

更好”的原因
boolean falsy = false;
if(falsy) {
    System.out.println("This should never happen");
}
if(!falsy) {
    System.out.println("This should always happen");
}

而不是

boolean falsy = false;
if(falsy == true) {
    System.out.println("This should never happen");
}
if(falsy == false) {
    System.out.println("This should always happen");
}

当你输入错误时

boolean falsy = false;
if(falsy = true) {
    System.out.println("This should never happen."); // This happens
}
if(falsy = false) {
    System.out.println("This should always happen"); // This didn't happens
}