2014-10-05 138 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); 

}