В този пример ще се научим да проверяваме дали две от трите булеви променливи са верни в 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;