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

c6ubokkw  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(408)

我得到一个用户输入,并使用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;
}
cu6pst1q

cu6pst1q1#

这将永远持续下去,因为一个非常明显的原因:你不是每次都在做一个新病人,因为这条线

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

}
bxjv4tth

bxjv4tth2#

removepatient没有改变,只有deletelname。因此,为了解决您的问题,请添加 removePatient = new Patient (deletelName.toLowerCase(),null,null,null,null); 在你循环的最后。

相关问题