У цьому прикладі ми навчимося перевіряти, чи є дві з трьох булевих змінних істинними в Java.
Щоб зрозуміти цей приклад, ви повинні знати такі теми програмування Java:
- Заява про Java, якщо … ще
- Тернарний оператор Java
Приклад: Перевірте, чи є дві з трьох булевих змінних істинними
// 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(); ) )
Вихід 1
Введіть перше логічне значення: true Введіть друге логічне значення: false Введіть третє логічне значення: true Дві логічні змінні є істинними.
Вихід 2
Введіть перше логічне значення: false Введіть друге логічне значення: true Введіть третє логічне значення: false Дві логічні змінні не відповідають дійсності.
У наведеному вище прикладі ми маємо три логічні змінні з іменами first, second і third. Тут ми перевірили, чи є дві логічні змінні серед трьох істинними чи ні.
Ми використовували if… else
оператор, щоб перевірити, чи є дві логічні змінні істинними чи ні.
if(first) ( result = second || third; ) else ( result = second && third; )
Тут замість if… else
твердження ми також можемо використовувати тернарний оператор.
result = first ? second || third : second && third;