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

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

我得到一个用户输入,并使用while循环不断验证输入。但是,无论我输入的输入类型应该是真的,它都会不断返回false并重复循环。
这是使用循环的代码部分:

  1. String deletelName;
  2. System.out.println("Type patient's last name to delete");
  3. deletelName = cin.next();
  4. Patient removePatient = new Patient (deletelName.toLowerCase(),null,null,null,null);
  5. while (!bst.contains(removePatient)) {
  6. System.out.println("Patient's last name does not exist. Type another last name : ");
  7. deletelName = cin.next();
  8. }

bst课程的一部分:

  1. public boolean contains(AnyType x)
  2. {
  3. return contains(x, root);
  4. }
  5. private boolean contains(AnyType x, BinaryNode<AnyType> t)
  6. {
  7. if (t == null)
  8. return false;
  9. int compareResult = x.compareTo(t.element);
  10. if(compareResult < 0)
  11. return contains(x, t.left);
  12. else if (compareResult > 0)
  13. return contains (x, t.right);
  14. else
  15. return true;
  16. }
cu6pst1q

cu6pst1q1#

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

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

不在while循环中,因此它总是使用相同的 Patient . 解决方案是:

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

像这样:

  1. Patient removePatient = new Patient (deletelName.toLowerCase(),null,null,null,null);
  2. while (!bst.contains(removePatient)) {
  3. System.out.println("Patient's last name does not exist. Type another last name : ");
  4. deletelName = cin.next();
  5. removePatient = new Patient (deletelName.toLowerCase(),null,null,null,null);
  6. }
展开查看全部
bxjv4tth

bxjv4tth2#

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

相关问题