【问题标题】:while loop keeps repeating when it's not supposed towhile 循环在不应该重复时不断重复
【发布时间】:2016-03-28 07:15:17
【问题描述】:

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

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

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

【问题讨论】:

  • 什么是bst?您需要提供比这更多的代码。

标签: java while-loop


【解决方案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);

}

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 我用更长的方式写了同样的东西,而你在那个时间段内回答了:D 我认为我们都是正确的,所以我 +1 :)
    猜你喜欢
    • 2011-11-23
    • 1970-01-01
    • 2016-10-02
    • 1970-01-01
    • 1970-01-01
    • 2019-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多