2016-11-28 19 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

相关问题