जावा प्रोग्राम यह जाँचने के लिए कि क्या दो बूलियन चर दो सही हैं

इस उदाहरण में, हम यह जांचना सीखेंगे कि जावा में तीन बूलियन चर में से दो सही हैं या नहीं।

इस उदाहरण को समझने के लिए, आपको निम्नलिखित जावा प्रोग्रामिंग विषयों का ज्ञान होना चाहिए:

  • जावा अगर … और स्टेटमेंट
  • जावा टर्नरी ऑपरेटर

उदाहरण: जांचें कि क्या तीन बूलियन चर में से दो सत्य हैं

 // 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

 पहली बूलियन मान दर्ज करें: सही दूसरी बूलियन मान दर्ज करें: झूठी तीसरी बूलियन मान दर्ज करें: सच दो बूलियन चर सत्य हैं।

आउटपुट 2

 पहला बूलियन मान दर्ज करें: गलत दूसरा बूलियन मान दर्ज करें: सत्य तीसरा बूलियन मान दर्ज करें: गलत दो बूलियन चर सत्य नहीं है।

उपरोक्त उदाहरण में, हमारे पास पहले, दूसरे और तीसरे नाम के तीन बूलियन चर हैं। यहाँ, हमने जाँच की है कि तीन में से दो बूलियन चर सही हैं या नहीं।

हमने if… elseबयान का उपयोग यह जांचने के लिए किया है कि दो बूलियन चर सही हैं या नहीं।

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

यहां, if… elseबयान के बजाय , हम टर्नरी ऑपरेटर का उपयोग भी कर सकते हैं।

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

दिलचस्प लेख...