2012-02-06 38 views
2

我想創建一個返回三個值(全部字節)的最小值的方法。這是我的:將三個數字與Java邏輯三元運算符進行比較?

public static byte findSmallestOfThree(byte n1, byte n2, byte n3) { 
    return n1 > n2 ? n2 : n1 > n3 ? n3 : n1; 
} 

現在,我遇到的問題是,它並不總是工作。

這裏有一些輸入,輸出:

9, 10, 11 -> 9 

10, 9, 11 -> 9 

10, 11, 9 -> 9 

11, 10, 9 -> 10 

正如你可以看到,當我進入11,10,9(按順序),我得到了10的結果(即使它應該已經9)。

我的邏輯有什麼問題?我認爲我已經搞砸了三元運營商的東西,但我不知道它是什麼...

+2

我愛三元運算儘可能未來的傢伙;但這種ascii的歪曲很好地說明了爲什麼三元組不應該像這樣鏈接。當然,我*可以*坐在這裏,假裝是javacc,並找出嵌套的位置在哪裏......但我更願意看到幾個能夠解除我職責的el-elses。這裏的其他答案表明你精神上混淆了你的比較;當你在一個聲明中嘗試做太多時,這很容易做到! – yshavit 2012-02-07 00:00:18

回答

4

它與三元運營商不是一個錯誤;這是比較的錯誤。你的代碼說:如果n1> n2,返回n2。因此,在第四個例子中,11> 10,因此它返回10.

您必須將n1與n2和n3進行比較,以瞭解它是最大還是最小。你真的想要的東西像

return (n1 <= n2) && (n1 <= n3) ? n1 : (n2 <= n3)? n2 : n3 

(注:沒有實際測試過)

+1

你可以刪除'=' – 2012-02-07 00:08:25

0
byte min = n1 < n2 ? n1 : n2; 
return min < n3 ? min : n3; 
1

這個工作對我來說(我讓他們int更容易測試):

public static int findSmallestOfThree(int n1, int n2, int n3) { 
    return n1 < n2 ? n1 < n3 ? n1 : n3 : n2 < n3 ? n2 : n3; 
} 

如果你關心更多關於可讀性比速度:

public static int findSmallestOfThree(int n1, int n2, int n3) { 
    return Math.min(n1, Math.min(n2, n3)); 
} 

下面是一些簡單的測試代碼:

public static void main(String[] args) { 
    System.out.println(findSmallestOfThree(9, 10, 11)); 
    System.out.println(findSmallestOfThree(10, 9, 11)); 
    System.out.println(findSmallestOfThree(10, 11, 9)); 
    System.out.println(findSmallestOfThree(11, 10, 9)); 
    System.out.println(findSmallestOfThree(9, 11, 10)); 
    System.out.println(findSmallestOfThree(11, 9, 10)); 
} 
0

要獲得最大值出三個數字中,一行的方法:

INT分鐘=(一個< b & &一個< C)? a :((b < a & & b < c)?b:c);

0

代碼找到最大的三個號碼的使用三元運算符:

public class FindGraterUsingTernaryOperator { 
    public static void main(String[] args) { 
    Scanner sc = new Scanner(System.in); 
    System.out.println("Enter the 3 Numbers to Check the Grater:::"); 
    int a = sc.nextInt(); 
    int b = sc.nextInt(); 
    int c = sc.nextInt(); 
    int result = c > (a > b ? a : b) ? c : ((a > b) ? a : b); 
    System.out.println("Grater Between 3 Numbers Is::" + result); 
    } 
}