2013-11-03 19 views
0

我有一個for循環設置,通過每個項目迭代中的對象的陣列。我有一個if語句,用於檢查某個項目中的值是否與特定的字符串值匹配。如果是這樣,我想把它打印到屏幕上。這樣做我沒有問題。但是,如果循環完成而沒有找到匹配,我希望程序打印一條錯誤消息。我現在將它設置爲if else語句,如果它不匹配,程序將爲每個項目打印一條錯誤消息。我無法找到一種方法,只有當循環結束時才這樣做。任何指導將不勝感激。通過陣列迭代和檢查每個項目,打印錯誤如果沒有匹配

+3

循環之前設置一個'布爾matchFound'爲false,將其設置爲true,如果你找到的東西,並打印錯誤信息,如果它是在lo之後是假的運。 – Keppil

+0

@Keppil你能否提出這樣的答案,以便它可以被提高和(可能)被接受? –

回答

0

創建一個布爾變量來存儲匹配是否已被發現。在循環運行之前將其設置爲false,如果在循環中找到匹配項,則將其設置爲true。如果在循環結束後它仍然是錯誤的,則打印出錯信息。

1

在代碼中使用以下模式:

boolean matchFound = false; 
for (item: objects) { 
    if (item.equals(stringValue) { 
     //print item the same way as you did 
     matchFound = true; 
    } 
} 
if (!matchFound) { 
    System.out.println("No match found!"); 
} 
+0

具有諷刺意味的是我們的答案如此相似以至於他們看起來像我抄襲了你:D –

0
boolean matchFound = false; // dont be so eager that there is a match 
for(String each : lotOfStrings){ 
    if(each.equals(someOtherStrings)){ 
     matchFound = true; 
     // break; // optionally, you may break out 
    } 
} 

if(!matchFound){ // no match found? 
    System.out.println("Error"); 
}else{ 
    System.out.println("Found a match");  
} 

上面的代碼片段顯示瞭如何實現你想要的。

基於Keppil的評論

0

由於Keppil建議,優化一點點:

boolean matchFound = false; 
for (int i = start; i < max && boolean == false; i++) { 
    if (foundElement()) { 
     matchFound = true; 
    } 
} 
if (!matchFound) { 
    log.error = ""; 
} 

,或者你可以做

int i = start; 
for (; i < max; i++) { 
    if (foundElement()) { 
     break; 
    } 
} 
if (i == max) { 
    log.error = ""; 
} 
0

Keppil和小孩有很好的解決方案,但讓我建議一個重構,這使得這個問題更容易處理,因爲你的規格改變了。也許矯枉過正。分解算法的步驟。 首先,獲得比賽的名單。 然後,決定與他們做什麼。例如(你最終想要打破這種代碼以及)

ArrayList<T> matches = new ArrayList<T>; // T is your object type, e.g. String 
for (T item : myObjects) { 
    if (item.equals(thingToMatch)) 
     matches.add(item); 
} 

//現在,決定做什麼與列表...

if (matches.size() > 0) { 
    for (T t : matches) 
     // print it here 
     // but in the future could log them, store in a database, convert to XML, etc... 
} 
else 
    System.out.println("no matches were found to " + thingToMatch); 
0

如果您不需要特定的匹配的對象,那麼最清潔的方式來照顧你的關注是通過寫一個幫助者的方法來發現。這樣就可以避免局部變量的分配和再分配和代碼變得相當多的清潔劑:

boolean find(List<?> list, Object toFind) { 
    for (Object o : list) if (o.equals(toFind)) return true; 
    return false; 
} 

這工作對字符串列表,以及任何其他對象。在main方法,你可以寫

System.out.println((find(list, toFind)? "A" : "No") + " match was found"); 

如果你需要的所有匹配對象,那麼我會再次建議將返回所有匹配列表的helper方法,讓你打印或處理任何其他方式:

<T> List<T> getMatches(List<T> list, Object toFind) { 
    final List<T> ret = new ArrayList<>(); 
    for (T x : list) if (t.equals(toFind)) ret.add(x); 
    return ret; 
} 

現在,在調用方法,你可以有

final List<MyType> matches = find(inputList, toFind); 
if (matches.isEmpty()) System.out.println("No match was found"); 
else { ... process the list as needed ... }