本当に必要がないときに、z をテストしています。三項演算子は cond ? の形式でなければなりません。ifTrue : ifFalse;
したがって、複数の条件がある場合は、次のようになります。
条件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.");
}
}