1. Secuencia de ifdeclaraciones

A veces, un programa necesita realizar muchas acciones diferentes según el valor de una variable o el valor de una expresión.

Digamos que nuestra tarea es algo como esto:

  • Si la temperatura es superior a 20los grados, entonces póngase una camisa.
  • Si la temperatura es mayor a 10grados y menor (o igual a) 20entonces ponte un suéter
  • Si la temperatura es mayor a 0grados y menor (o igual a) 10entonces ponte un chubasquero
  • Si la temperatura es inferior a 0grados, póngase un abrigo.

Así es como esto se puede representar en el código:

int temperature = 9;

if (temperature > 20)
   System.out.println("put on a shirt");
else // Here the temperature is less than (or equal to) 20
{
   if (temperature > 10)
      System.out.println("put on a sweater");
   else // Here the temperature is less than (or equal to) 10
   {
      if (temperature > 0)
         System.out.println("put on a raincoat");
      else // Here the temperature is less than 0
         System.out.println("put on a coat");
   }
}

If-elseLas sentencias se pueden anidar unas dentro de otras. Esto hace posible implementar una lógica bastante compleja en un programa.

Pero el ejemplo anterior también es interesante porque podemos simplificar un poco el código omitiendo las llaves:

int temperature = 9;

if (temperature > 20)
   System.out.println("put on a shirt");
else // Here the temperature is less than (or equal to) 20
   if (temperature > 10)
      System.out.println("put on a sweater");
   else // Here the temperature is less than (or equal to) 10
      if (temperature > 0)
         System.out.println("put on a raincoat");
      else // Here the temperature is less than 0
         System.out.println("put on a coat");

Sin embargo, los programadores suelen escribir esta construcción de forma un poco diferente:

int temperature = 9;

if (temperature > 20)
   System.out.println("put on a shirt");
else if (temperature > 10) // Here the temperature is less than (or equal to) 20
   System.out.println("put on a sweater");
else if (temperature > 0) // Here the temperature is less than (or equal to) 10
   System.out.println("put on a raincoat");
else // Here the temperature is less than 0
   System.out.println("put on a coat");

Los tres ejemplos son equivalentes.


2. Matices del elsebloque.

Un punto importante:

Si no usa llaves en una if-elseconstrucción, entonces se elserefiere al anterior más cercano if.

Ejemplo:

nuestro código ¿Cómo funcionará?
int age = 65;

if (age < 60)
   if (age > 20)
      System.out.println("You must work");
else
   System.out.println("You don't have to work");
int age = 65;

if (age < 60)
{
   if (age > 20)
     System.out.println("You must work");
   else
     System.out.println("You don't have to work");
}

Si observa el código de la izquierda, parece que la salida de la pantalla será "No tiene que trabajar". Pero ese no es el caso. En realidad, el elsebloqueo y la declaración "No tienes que trabajar" están asociados con la segunda ifdeclaración (la más cercana).

En el código de la derecha, los asociados ify elseestán resaltados en rojo. Además, las llaves se colocan sin ambigüedades, lo que muestra claramente qué acciones se realizarán. ¿La cadena You don't have to work nunca se muestra cuando agees mayor que 60?



3. Ejemplo de uso de una if-elsedeclaración

Ya que exploramos la if-elsedeclaración tan bien, demos un ejemplo:

import java.util.Scanner;
public class Solution {
   public static void main(String[] args)
   {
     Scanner console = new Scanner(System.in); // Create a Scanner object
     int a = console.nextInt(); // Read the first number from the keyboard
     int b = console.nextInt(); // Read the second number from the keyboard
     if (a < b)                   // If a is less than b
       System.out.println(a);     // we display a
     else                         // otherwise
       System.out.println(b);     // we display b
   }
}
Mostrar el mínimo de dos números