Programma Java per verificare se due delle tre variabili booleane sono vere

In questo esempio, impareremo a controllare se due delle tre variabili booleane sono vere in Java.

Per comprendere questo esempio, è necessario conoscere i seguenti argomenti di programmazione Java:

  • Istruzione Java if … else
  • Operatore ternario Java

Esempio: controlla se due delle tre variabili booleane sono vere

 // Java Program to check if 2 variables // among the 3 variables are true import java.util.Scanner; class Main ( public static void main(String() args) ( // create 3 boolean variables boolean first; boolean second; boolean third; boolean result; // get boolean input from the user Scanner input = new Scanner(System.in); System.out.print("Enter first boolean value: "); first = input.nextBoolean(); System.out.print("Enter second boolean value: "); second = input.nextBoolean(); System.out.print("Enter third boolean value: "); third = input.nextBoolean(); // check if two are true if(first) ( // if first is true // and one of the second and third is true // result will be true result = second || third; ) else ( // if first is false // both the second and third should be true // so result will be true result = second && third; ) if(result) ( System.out.println("Two boolean variables are true."); ) else ( System.out.println("Two boolean variables are not true."); ) input.close(); ) )

Uscita 1

 Immettere il primo valore booleano: true Immettere il secondo valore booleano: false Immettere il terzo valore booleano: true Due variabili booleane sono vere.

Uscita 2

 Immettere il primo valore booleano: false Immettere il secondo valore booleano: true Immettere il terzo valore booleano: false Due variabili booleane non sono vere.

Nell'esempio precedente, abbiamo tre variabili booleane denominate prima, seconda e terza. Qui, abbiamo verificato se due delle variabili booleane tra le tre sono vere o meno.

Abbiamo utilizzato l' if… elseistruzione per verificare se due variabili booleane sono vere o meno.

 if(first) ( result = second || third; ) else ( result = second && third; )

Qui, al posto if… elsedell'istruzione, possiamo anche usare l'operatore ternario.

 result = first ? second || third : second && third;

Articoli interessanti...