Šiame pavyzdyje išmoksime patikrinti, ar du iš trijų loginių kintamųjų yra teisingi „Java“.
Norėdami suprasti šį pavyzdį, turite žinoti šias Java programavimo temas:
- „Java“, jei… kitas pareiškimas
- „Java Ternary“ operatorius
Pavyzdys: patikrinkite, ar teisingi du iš trijų loginių kintamųjų
// 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 rezultatas
Įveskite pirmąją loginę vertę: true Įveskite antrąją loginę vertę: false Įveskite trečiąją loginę reikšmę: true Du loginiai kintamieji yra teisingi.
2 išėjimas
Įveskite pirmąją loginę vertę: false Įveskite antrąją loginę vertę: true Įveskite trečiąją loginę reikšmę: false Du loginiai kintamieji nėra teisingi.
Ankstesniame pavyzdyje mes turime tris loginius kintamuosius, pavadintus pirmu, antru ir trečiu. Čia mes patikrinome, ar du loginiai kintamieji iš trijų yra teisingi, ar ne.
Mes naudojome if… else
teiginį, kad patikrintume, ar du loginiai kintamieji yra teisingi, ar ne.
if(first) ( result = second || third; ) else ( result = second && third; )
Čia vietoj if… else
teiginio galime naudoti ir trijų komponentų operatorių.
result = first ? second || third : second && third;