w3schools ternario signo que operador interrogacion ejemplos java operator-keyword ternary

signo - operador ternario return java



MĂșltiples condiciones en operadores ternarios. (11)

En primer lugar, la pregunta es "Escriba un programa Java para encontrar el menor de los tres números usando operadores ternarios".

Aquí está mi código:

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."); } }

Intenté usar varias condiciones en el operador ternario, pero eso no funciona. Estuve ausente unos días, así que no estoy muy seguro de qué hacer y el teléfono de mi maestro está apagado. ¿Alguna ayuda?


Estás probando para z, cuando realmente no lo necesitas. Su operador ternario debe ser de forma cond? ifTrue: ifFalse;

así que si tienes múltiples condiciones, tienes esto:

cond1? ifTrue1: cond2? si es True2: ifFalse2;

Si entiendes esto, no mires abajo. Si aún necesitas ayuda, mira abajo.

También incluí una versión que no los anida que sea más clara (asumiendo que no es necesario anidarlos. ¡Espero que tu tarea no requiera que los anules porque eso es bastante feo!)

.

.

Esto es lo que se me ocurre:

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."); } }


Esta respuesta llegará siete años tarde, así que solo te daré el código:

int smallestNumber = (x > y) ? ((y > z) ? z : y) : ((x > z) ? z : x);

La sangría debe explicar el código, que es simplemente un ternario que evalúa otros ternarios en la condición inicial x > y ; / * el primer ternario se evalúa si esa condición es verdadera, de lo contrario, el segundo se evalúa. * /


La última parte: (z<y && z<x) ? z (z<y && z<x) ? z le falta un '':'':

(z<y && z<x) ? z : some_value;


La mejor manera de hacer esto es hacer un ejemplo usando la instrucción if y else y luego aplicar los operadores ternarios en ella (q


Mi contribución ...

public static int getSmallestNumber( int x, int y, int z) { return x < y && x < z ? x : y < x && y < z ? y : z; } public static void main ( String ... args ) { System.out.println( getSmallestNumber( 123, 234, 345 ) ); }


Mi solución:

public static void main(String args[]) { int x = 1, y = 2, z = 3; int smallestNum = (x < y && x < z) ? x : (y < x && y < z) ? y : (z < y && z < x) ? z:y; System.out.println(smallestNum + " is the smallest of the three numbers."); }


Sé que es tarde. Solo para información esto también funciona:

int smallestNum = (x<y ? x : (x=y)) < z ? x : z


Tratar

int min = x < y ? (x < z ? x : z) : (y < z ? y : z);

También puede eliminar el paréntesis:

int min = x < y ? x < z ? x : z : y < z ? y : z;


Ya que esta es la tarea, no solo le voy a dar la respuesta, sino un algoritmo para que pueda resolverlo usted mismo.

Primero resuelva cómo escribir min (x, y) usando un solo operador ternario.

Una vez que tenga eso, cambie el siguiente código por min (x, y, z) para usar un operador ternario y luego sustituya en el código por min (x, y) que trabajó en el paso anterior.

int min(x, y, z) { if (x <= y) { return min(x, z); } else { return min(y, z); } }


int min = (x<y)?((x<z)?x:z):((y<z)?y:z);


public static int min(int x, int y, int z) { return x<y?Math.min(x, z):Math.min(y, z); } public static void main(String[] args) { int smallestNum = min(10, 12, 15); System.out.println(smallestNum); }