2015-05-17 36 views
-2

假設我有三個類,每個類都有一個int變量,它表示一個隊列:q1,q2和q3。所有變量至少爲零,並且不斷變化。此外,三個類中的每一個都有一個布爾字段:shortestQueue1,shortestQueue2和shortestQueue3。我需要一個方法,它在給定的時間比較q1,q2和q3,並將相應的shortestQueue變量設置爲true,其他兩個設置爲false。如果兩者同樣小,則名稱中具有最小數字的變量被設置(q1在q2上,q2在q3上)。高效地找到最短隊列

有沒有其他的方式,而不是寫很多if/else語句?

+0

您是否已經有任何代碼示例? – chris

+0

提供您的代碼。您可以使用具有隊列長度的字段並對它們進行比較。 – Bubletan

+0

那麼,我可以寫出很多if語句:if(q1 == q2 && q2 Arthur

回答

4

我相信你並不真的需要27個IFS 3個變量... 3應該做的......

更換System.outs,不管你需要做的,你的布爾值。

if(q1<=q2 && q1<=q3){   // q1 is the smallest 
     System.out.println("q1"); 
    } else if (q2<=q3) {   // q2 is smaller than q3, we have tested q1 in the previous if 
     System.out.println("q2"); 
    } else {      // if neither q1 nor q2 is the smallest, it has to be q3 
     System.out.println("q3"); 
    }