2013-12-19 47 views
0

我是新來的編程,並試圖創建一個迭代列表並返回true或false的方法來檢查比薩是否適合素食者。只有列表中的所有配料適合素食者纔是真實的。檢查清單的真或假

這裏是我的方法:

public boolean vegStatus(){ 

    boolean veg1 = false; 

    for(PizzaTopping topping : topList){ 
     if((topping.isVeg() == true)) { 
      veg1 = true; 
     } 
     else if(topping.isVeg() == false) { 
      veg1 = false; 
     } 
    } 
    return veg1; 
} 

這種方法行不通,它產生錯誤的答案。我該如何改變它,以便查看列表中的所有配料,並且只有在所有素食都適合的情況下才會返回true。

+1

只是返回假第二你發現一個不是蔬菜的打頂。 –

回答

3

下面是一個乾淨的邏輯:

public boolean vegStatus(){ 
    for(PizzaTopping topping : topList) { 
     if(!topping.isVeg()) 
      return false; 
    } 

    return true; 
} 

它檢查所有Toppings,如果他們中任何一個不吃素,它返回false馬上和不檢查其他人(不必,對吧?)。如果它檢查了所有這些,並且它們都不是Veg,它將返回true

0

只要記住,當頂部不素食,你不需要關心其餘的配料,沒有什麼可以改變比薩後的狀態。因此,沒有必要檢查其餘的。 返回簡單地打破所有循環。如果素食者不喜歡的東西沒有污染比薩餅,你知道它必須是素食主義者。

public boolean vegStatus(){ 

    for(PizzaTopping topping : topList){ 
     if(!topping.isVeg()) { 
      return false; 
     } 

    } 
    return true; 
} 
0
public boolean vegStatus(){ 

    boolean veg1 = false; 

    for(PizzaTopping topping : topList){ 
     if((topping.isVeg() == true)) { 
      veg1 = true; 
     } 
     else { 
      return false; 
     } 
    } 
    return veg1; 
} 
0

您應該veg1變量初始化爲真,內環路只有改變它,如果你找到一個摘心是不適合素食者。

public boolean vegStatus(){ 

    boolean veg1 = true; 

    for(PizzaTopping topping : topList){ 
     if(topping.isVeg() == false) { 
      veg1 = false; 
     } 
    } 
    return veg1; 
} 
0

做這樣

public boolean vegstatus(){  
    for(PizzaTopping topping : topList){ 
     if(!topping.isVeg()) { 
      return false; //Failed so anymore he is not a vegetarian 
     }  
    } 
    return true;// Never failed above condition so he should be vegetarian. 
} 
+1

無需檢查是否爲真:-) –

0

你應該做這樣的....

public boolean vegStatus(){ 

boolean veg1 = true; // by default its true 

for(PizzaTopping topping : topList){ 
    if(topping.isVeg() == false) { 
     veg1 = false; // if any one id not suitable then its false 
    } 
} 
return veg1; // at the end returning the result.. 
} 

如果您有任何疑問,那麼你可以再問...