2014-10-05 120 views
0

这里我的问题是,当我在数组中有2个对象时,它会循环2x,然后请求另一个“你确定要删除它吗?”。无法弄清楚我的循环。这里是代码:在Arraylist中删除对象

for (Iterator<Student> it = student.iterator(); it.hasNext();) { 

    Student stud = it.next(); 
    do { 
     System.out.print("Are you sure you want to delete it?"); 
     String confirmDelete = scan.next(); 

     ynOnly = false; 

     if (confirmDelete.equalsIgnoreCase("Y") 
       && stud.getStudNum().equals(enterStudNum2)) { 
      it.remove(); 
      System.out.print("Delete Successful"); 
      ynOnly = false; 
     } else if (confirmDelete.equalsIgnoreCase("N")) { 
      System.out.print("Deletion did not proceed"); 
      ynOnly = false; 
     } else { 
      System.out.println("\nY or N only\n"); 
      ynOnly = true; 
     } 
    } while (ynOnly == true); 

} 
+0

你应该明白之间的差别了'做/ while'循环和'while'循环:) – nem035 2014-10-05 04:47:21

+0

@Trafalgar法:对于两个对象的名单,你应该看到“你确定...?”两次,并且“删除成功”两次,假设您为循环的每次迭代按'y'/'Y',并且'stud.getStudNum()。equals(enterStudNum2)'为'true'。你的输出是什么? – Voicu 2014-10-05 04:51:19

+0

@Voicu输出是这样的.. 删除成功 您确定要删除它吗? 它要求另一个确认 ,而不是只有一个确认 – 2014-10-05 06:04:56

回答

0

它是因为有两个循环在那里。在ynOnly的值变为false但外循环仍然继续之后,内循环终止。您可能要像that--

for (Iterator<Student> it = student.iterator(); it.hasNext();) { 

Student stud = it.next(); 
if(!stud.getStudNum().equals(enterStudNum2)) 
      continue;       //you want only that student to be deleted which has enterStudNum2 so let other record skip 
do { 
    System.out.print("Are you sure you want to delete it?"); 
    String confirmDelete = scan.next(); 

    ynOnly = false; 

    if (confirmDelete.equalsIgnoreCase("Y") 
      && stud.getStudNum().equals(enterStudNum2)) { 
     it.remove(); 
     System.out.print("Delete Successful"); 
     ynOnly = false; 
    } else if (confirmDelete.equalsIgnoreCase("N")) { 
     System.out.print("Deletion did not proceed"); 
     ynOnly = false; 
    } else { 
     System.out.println("\nY or N only\n"); 
     ynOnly = true; 
    } 
} while (ynOnly == true); 

}