while循环在不应该的时候不断重复

时间:2016-03-27 23:04:37

标签: java while-loop

我正在获取用户输入并使用while循环来继续验证输入。 但是,无论我输入什么类型的输入都应该是真的,它会一直返回false并重复循环。

这是使用循环的代码部分:

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

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

2 个答案:

答案 0 :(得分:1)

removePatient不会改变,只有deletelName。因此,为了解决您的问题,请在循环结束时添加removePatient = new Patient (deletelName.toLowerCase(),null,null,null,null);

答案 1 :(得分:1)

这将永远持续下去,原因很明显:你每次都没有新病人因为这条线

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

不在while循环中,因此它始终使用相同的Patient进行检查。解决方案是替换它:

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

有这样的事情:

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

}