1. Sequenza di ifdichiarazioni
A volte un programma deve eseguire molte azioni diverse a seconda del valore di una variabile o del valore di un'espressione.
Diciamo che il nostro compito è qualcosa del genere:
- Se la temperatura è superiore a
20gradi, indossa una maglietta - Se la temperatura è maggiore di
10gradi e minore di (o uguale a)20, allora indossa un maglione - Se la temperatura è maggiore di
0gradi e minore di (o uguale a)10, allora indossa un impermeabile - Se la temperatura è inferiore a
0gradi, indossa un cappotto.
Ecco come questo può essere rappresentato nel codice:
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-elseistruzioni possono essere annidate l'una nell'altra. Ciò rende possibile implementare una logica piuttosto complessa in un programma.
Ma l'esempio precedente è interessante anche in quanto possiamo rendere il codice un po' più semplice omettendo le parentesi graffe:
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");
Tuttavia, i programmatori di solito scrivono questo costrutto in modo leggermente diverso:
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");
Tutti e tre questi esempi sono equivalenti.
2. Sfumature del elseblocco
Se non si usano le parentesi graffe in un if-elsecostrutto, allora fa elseriferimento al precedente più vicino if.
Esempio:
| Il nostro codice | Come funzionerà |
|---|---|
|
|
Se guardi il codice a sinistra, sembra che l'output dello schermo sarà "Non devi lavorare". Ma non è così. In realtà, il elseblocco e l'affermazione "Non devi lavorare" sono associati alla seconda ifaffermazione (la più vicina).
Nel codice a destra, gli associati ife elsesono evidenziati in rosso. Inoltre, le parentesi graffe sono posizionate in modo inequivocabile, mostrando chiaramente quali azioni verranno eseguite. La stringa Non devi lavorare non viene mai visualizzata quando ageè maggiore di 60?
3. Esempio di utilizzo di if-elseun'istruzione
Dato che abbiamo esplorato if-elsecosì bene l'affermazione, facciamo un esempio:
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
}
}
GO TO FULL VERSION