2016-11-22 78 views
-7

因此,我試圖檢查多個布爾值(6),並且如果超過一個,兩個,三個等是真的,則要執行不同的代碼。檢查布爾值是否爲真,並根據數量執行不同的值

所以這裏有一個例子:

public static boolean x; 
public static boolean y; 
public static boolean z; 
public static boolean a; 
public static boolean b; 
public static boolean c; 
public static int amtTrue; 
//if x & y are true, then set amtTrue to 1 
//if y & z AND x & y are true, then set amtTrue to 2; 
//keep iterating though all possiblilites 

什麼是做到這一點的最有效方法是什麼?

謝謝你的時間!

+1

你能提供一個這樣的例子?很難說出你在問什麼。 –

+0

這是確實非常廣泛,你問的問題! – vlatkozelka

+2

這些布爾值是否在數組中?在6個變量?在列表中?在房子裏?用鼠標? – samgak

回答

4
int i = 0; 

for(boolean b : array) 
    if(b) i++; 

switch(i){ 
case 0: 

case 1: 

case 2: 

} 
2

只有六個布爾型效率根本不應該影響,因此您可以專注於製作最易讀的解決方案。

一種方法是使一個可變參數的輔助方法,做計數的循環,像這樣:

public static int countTrue(boolean... x) { 
    int count = 0; 
    for (boolean b : x) { 
     if (b) { 
      count++; 
     } 
    } 
    return count; 
} 

您可以從if條件叫它如下,對於易於讀解:

if (countTrue(bool1, bool2, bool3, bool4, bool5, bool6) > 4) { 
    ... 
} 

Demo.