简体   繁体   English

当不应该循环时,while循环不断重复

[英]while loop keeps repeating when it's not supposed to

I am getting a user input and using a while loop to keep validating the input. 我正在获取用户输入,并使用while循环来继续验证输入。 However, no matter what type of input I enter that is supposed to be true, it keeps returning false and repeating the loop. 但是,无论我输入哪种输入都应该是真实的,它都会不断返回false并重复循环。

This is the section of the code that uses the loop: 这是使用循环的代码部分:

String deletelName;

System.out.println("Type patient's last name to delete");
deletelName = cin.next();   

Patient removePatient = new Patient (deletelName.toLowerCase(),null,null,null,null);

while (!bst.contains(removePatient)) {
    System.out.println("Patient's last name does not exist. Type another last name : ");
    deletelName = cin.next();
}   

Part of the bst class: bst类的一部分:

public boolean contains(AnyType x)
{
    return contains(x, root);
}


private boolean contains(AnyType x, BinaryNode<AnyType> t)
{
    if (t == null)
        return false;

    int compareResult = x.compareTo(t.element);

    if(compareResult < 0)
        return contains(x, t.left);

    else if (compareResult > 0)
        return contains (x, t.right);
    else
        return true;
}

removePatient isn't changing, only deletelName. removePatient不变,只有deletelName不变。 So in order to fix your problem, add in removePatient = new Patient (deletelName.toLowerCase(),null,null,null,null); 因此,为了解决您的问题,请添加removePatient = new Patient (deletelName.toLowerCase(),null,null,null,null); at the end of your loop. 在循环结束时。

This will go on forever for a very obvious reason: you are not making a new patient each time because this line 这将永远持续下去,这有一个非常明显的原因:您不会每次都在招募新患者,因为这条线

Patient removePatient = new Patient (deletelName.toLowerCase(),null,null,null,null);

is not in the while loop, and therefore it always checks with the same Patient . 不在while循环中,因此它总是与同一个Patient进行检查。 The solution is to replace this: 解决方案是替换为:

Patient removePatient = new Patient (deletelName.toLowerCase(),null,null,null,null);

while (!bst.contains(removePatient)) {
    System.out.println("Patient's last name does not exist. Type another last name : ");
    deletelName = cin.next();
}

With something like this: 用这样的东西:

Patient removePatient = new Patient (deletelName.toLowerCase(),null,null,null,null);

while (!bst.contains(removePatient)) {
    System.out.println("Patient's last name does not exist. Type another last name : ");
    deletelName = cin.next();
    removePatient = new Patient (deletelName.toLowerCase(),null,null,null,null);

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM