Šajā piemērā mēs iemācīsimies pārbaudīt, vai divi no trim Būla mainīgajiem ir patiesi Java.
Lai saprastu šo piemēru, jums jāpārzina šādas Java programmēšanas tēmas:
- Java, ja … cits paziņojums
- Java trīskāršais operators
Piemērs: pārbaudiet, vai divi no trim Būla mainīgajiem ir patiesi
// 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. izeja
Ievadiet pirmo būla vērtību: true Ievadiet otro būla vērtību: false Ievadiet trešo būla vērtību: true Divi būla mainīgie ir patiesi.
2. izeja
Ievadiet pirmo būla vērtību: false Ievadiet otro būla vērtību: true Ievadiet trešo būla vērtību: false Divi būla mainīgie nav patiesi.
Iepriekš minētajā piemērā mums ir trīs būla mainīgie, kas nosaukti pirmais, otrais un trešais. Šeit mēs esam pārbaudījuši, vai divi no Būla mainīgajiem lielumiem starp trim ir patiesi vai nav.
Mēs esam izmantojuši if… else
paziņojumu, lai pārbaudītu, vai divi Būla lielumi ir patiesi vai nav.
if(first) ( result = second || third; ) else ( result = second && third; )
Šeit if… else
paziņojuma vietā mēs varam izmantot arī trīskāršo operatoru.
result = first ? second || third : second && third;