我是Java新手,我試圖理解如何在for循環中嵌套if語句,並在if語句後退出for循環被執行。我有一個數組,for循環遍歷數組以查看ID是否存在,是否應該刪除它,如果它不存在,那麼它應該打印一條錯誤消息。發生的情況是條件是在while循環中的嵌套if語句中進行測試並打印錯誤消息3次。我希望它只打印一次錯誤消息。在while循環中測試條件,然後在Java中退出while循環
在我的主要方法,我在第一個它應該只是刪除ID和打印,這是REM,第二個它應該只打印錯誤信息一旦有
remove("3");
remove("3");
。這是一個針對學校的項目,不需要用戶輸入。我只是想了解如何使這項工作不打印出重複的錯誤消息
public static void remove(String studentID)
{
for (int i = 0; i < thestudents.size(); i++)
{
Student temp = thestudents.get(i);
if (temp.getStudentID()==(Integer.parseInt(studentID)))
{
thestudents.remove(i);
System.out.println("Student " + temp.getFirstName() + " was removed");
}
else
{
System.out.println("Student with ID " + studentID + " Was not found!");
}
}
}
結果:
Student with ID 3 Was not found! Student with ID 3 Was not found! Student Jack was removed Student with ID 3 Was not found! Student with ID 3 Was not found! Student with ID 3 Was not found! Student with ID 3 Was not found! Student with ID 3 Was not found!
後市展望:
Student Jack was removed Student with ID 3 Was not found!
謝謝!這工作。我之前使用了返回,但沒有將錯誤消息移到循環之外。再次感謝你! –