2016-11-28 17 views
0

我努力讓我的代碼做我想做的事。我有一個數組列表,其中包含自行車的年齡,型號,僱用號碼和製造商的詳細信息。在那份名單中,我想找到與匹配的僱員人數相匹配的自行車並更新其年齡。如果找不到匹配,我想打印'找不到匹配的自行車'。我在這裏的問題是我只希望該信息被打印一次,但每當我運行該程序它打印多次。我想找到一種方法來檢查整個列表,然後如果沒有匹配的僱員編號打印「找不到匹配的自行車」一次。如何搜索整個數組,然後返回1件事

public void updateAge(int hireNumber, int newAge) { 
    ArrayList<Bicycle> output = new ArrayList<>(); 
    for (Bicycle bicycle : bicycles){ 
     if (bicycle.getHireNumber()!=(hireNumber)){ 
      System.out.println("No matching bicycle found."); 
     } else { 
      bicycle.setAge(newAge); 
     } 
    } 
} 

回答

2

你可以,如果條件bicycle.getHireNumber() == hireNumber滿足聲明isFound標誌,並設置爲true如下圖所示:

ArrayList<Bicycle> output = new ArrayList<>(); 
boolean isFound = false; 

for(Bicycle bicycle : bicycles){ 
    if (bicycle.getHireNumber() == hireNumber) { 
      isFound = true; 
      bicycle.setAge(newAge); 
      return;//match found, so break & return 
    } 
    } 

//now check isFound is true, if not print it (only once) 
if(!isFound) { 
    System.out.println("No matching bicycle found."); 
} 
+0

甚至可以只返回和刪除'if'檢查 –

+0

非常感謝,使很有道理。 – Peter

+0

@ScaryWombat謝謝,我更新爲'return'而不是'break' – developer

相關問題