2016-10-15 246 views
2

我是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! 

回答

0

只要添加一個休息將在比賽結束後刪除輸出,但比賽前的輸出將保持不變。

我想你想擺脫所有的假陰性輸出。

因此,您必須在循環(刪除else行)後移動負輸出(else塊的內容),並確保在找到ID時不會執行此代碼。

執行此操作的最佳方法是在if塊中添加return作爲最後一條語句。

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"); 
     return; // leaving the method whe ID found 
    } 
} 
// is only executed when ID not found 
System.out.println("Student with ID " + studentID + " Was not found!)"; 
+0

謝謝!這工作。我之前使用了返回,但沒有將錯誤消息移到循環之外。再次感謝你! –

1

只需添加一個breakif聲明。如果if陳述是true,那麼循環將終止。

if (temp.getStudentID()==(Integer.parseInt(studentID))) { 
    hestudents.remove(i); 
    System.out.println("Student " + temp.getFirstName() + " was removed"); 
    break; 
} 
+1

正是!休息會是比收益更好的選擇; –

+0

_break將是比return_更好的選擇_不,它不是!在循環之後,一個「break」需要額外的邏輯來確定循環是否完成而沒有命中或者早期命中。這個額外的邏輯不需要'return'。 –

1

你可以使用一個break語句來終止循環,或者更好的是,一個return聲明中以完全終止方法一旦你找到合適的項目:

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"); 
      return; 
     } 
    } 

    // If we get here it means we haven't returned, so the student wasn't found 
    System.out.println("Student with ID " + studentID + " Was not found!"); 
} 
+0

那麼返回會停止執行,但是,它也會終止該方法。所以最後的聲明不會打印任何東西。另外,如果它本來是一個int類型的方法,那麼,你不能簡單地對'返回'。 –

+0

@RishabhKumar我們**希望**最後的聲明不會打印,因爲學生確實找到了。如果它不是'void'方法,那麼只需返回一個值。 – Mureinik