Java While循环布尔混淆

Java While循环布尔混淆,java,while-loop,Java,While Loop,为什么我的布尔t在while循环后被设置为false。我在while循环中放置了print语句和“if”条件,该循环设置t=false;永远不会被击中。为什么在for和while循环之间打印t时t=false public void addStudents(Student student){ System.out.println("in addStudents"); boolean t = true; int counter = 0; while ( t = tr

为什么我的布尔t在while循环后被设置为false。我在while循环中放置了print语句和“if”条件,该循环设置t=false;永远不会被击中。为什么在for和while循环之间打印t时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;
        }
    }
}
public void addstudent(学生){
System.out.println(“in-addStudents”);
布尔t=真;
int计数器=0;
while(t=true&&counter
问题在于运算符
&&
的优先级较高,如
=

因此,语句
t=true&&counter
被编译成
t=(true&&counter
,并且
t
总是在循环结束时设置为false

您可能想编写
t==true&&counter
,但键入错误
=

这就是为什么最好只写一篇文章的原因

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
}

while(t=true
可能应该是
while(t==true
while)(t=true
t=true
t
设置为true。您的意思是
while(t&&counter MyBooO[/COD]而不是<代码> MyBOOL=真的< /代码>和MyBoOL < /C> >而不是<代码> MyBOOL= = false < /Cord>。谢谢,我不知道我能做THA。T