三元运算符中的多个条件

Mik*_*ike 16 java ternary operator-keyword

首先,问题是"编写一个Java程序,使用三元运算符找到三个最小的数字."

这是我的代码:

class questionNine
{
    public static void main(String args[])
    {
        int x = 1, y = 2, z = 3;
        int smallestNum;

        smallestNum = (x<y && x<z) ? x : (y<x && y<z) ? y : (z<y && z<x) ? z;
        System.out.println(smallestNum + " is the smallest of the three numbers.");
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试在三元运算符中使用多个条件,但这不起作用.几天我不在,所以我不确定该做什么,老师的电话已关闭.有帮助吗?

Mar*_*son 27

尝试

int min = x < y ? (x < z ? x : z) : (y < z ? y : z);
Run Code Online (Sandbox Code Playgroud)

您也可以删除括号:

int min = x < y ? x < z ? x : z : y < z ? y : z;
Run Code Online (Sandbox Code Playgroud)

  • 无括号的版本看起来像是Obfuscated-C竞赛的入口. (30认同)

Mar*_*ers 14

由于这是作业,我不只是给你答案,而是一个算法,你可以自己解决.

首先研究如何使用单个三元运算符编写min(x,y).

完成后,将min(x,y,z)的以下代码更改为使用三元运算符,然后在代码中替换上一步中计算出的min(x,y).

int min(x, y, z) {
    if (x <= y) {
        return min(x, z);
    } else {
        return min(y, z);
    }
}
Run Code Online (Sandbox Code Playgroud)


cor*_*iKa 5

当您确实不需要时,您正在测试 z。你的三元运算符必须是 cond 形式?如果真:如果假;

所以如果你有多个条件,你有这个:

条件 1?ifTrue1:cond2?如果 True2 : ifFalse2;

如果你明白这一点,请不要往下看。如果您仍然需要帮助,请往下看。

我还包含了一个更清晰的不嵌套它们的版本(假设您不需要嵌套它们。我当然希望您的作业不需要您嵌套它们,因为那太丑了!)

.

.

这是我想出的:

class QuestionNine
{
    public static void main(String args[])
    {
        smallest(1,2,3);
        smallest(4,3,2);
        smallest(1,1,1);
        smallest(5,4,5);
        smallest(0,0,1);
    }

    public static void smallest(int x, int y, int z) {
        // bugfix, thanks Mark! 
        //int smallestNum = (x<y && x<z) ? x : (y<x && y<z) ? y :  z;
        int smallestNum = (x<=y && x<=z) ? x : (y<=x && y<=z) ? y :  z;
        System.out.println(smallestNum + " is the smallest of the three numbers.");
    }

    public static void smallest2(int x, int y, int z) {
       int smallest = x < y ? x : y; // if they are equal, it doesn't matter which
       smallest = z < smallest ? z : smallest;
       System.out.println(smallest + " is the smallest of the three numbers.");
    }
}
Run Code Online (Sandbox Code Playgroud)


ext*_*eon 1

最后一部分:(z<y && z<x) ? z缺少 ':' :

(z<y && z<x) ? z : some_value;
Run Code Online (Sandbox Code Playgroud)