ในบทความนี้ เราจะเข้าใจวิธีการตรวจสอบว่าตัวแปรบูลีนสองในสามตัวนั้นเป็นจริงหรือไม่ ตัวแปรบูลีนเป็นประเภทข้อมูลที่มีได้เฉพาะค่าจริงหรือเท็จเท่านั้น
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -
ป้อนข้อมูล
สมมติว่าข้อมูลที่เราป้อนคือ −
Input : true, true, false
ผลผลิต
ผลลัพธ์ที่ต้องการจะเป็น −
Result : Two of the three variables are true
อัลกอริทึม
Step 1 - START Step 2 - Declare 4 boolean values namely my_input_1, my_input_2, my_input_3 and my_result Step 3 - Read the required values from the user/ define the values Step 4 - Using an if-else condition, compare two of the three values each time using an AND operator. Step 5 - Display the result Step 6 – Stop
ตัวอย่างที่ 1
ที่นี่ ผู้ใช้ป้อนอินพุตตามข้อความแจ้ง คุณสามารถลองใช้ตัวอย่างนี้ในเครื่องมือกราวด์ของเรา .
import java.util.Scanner; public class BooleanValues { public static void main(String[] args) { boolean my_input_1, my_input_2, my_input_3, my_result; System.out.println("The required packages have been imported"); System.out.println("A scanner object has been defined "); Scanner my_scanner = new Scanner(System.in); System.out.print("Enter the first boolean value: "); my_input_1 = my_scanner.nextBoolean(); System.out.print("Enter the second boolean value: "); my_input_2 = my_scanner.nextBoolean(); System.out.print("Enter the third boolean value: "); my_input_3 = my_scanner.nextBoolean(); if(my_input_1) { my_result = my_input_2 || my_input_3; } else { my_result = my_input_2 && my_input_3; } if(my_result) { System.out.println("Two of the three variables are true"); } else { System.out.println("Two of the three variables are false"); } } }
ผลลัพธ์
The required packages have been imported A scanner object has been defined Enter the first boolean value: true Enter the second boolean value: true Enter the third boolean value: false Two of the three variables are true
ตัวอย่างที่ 2
ในที่นี้ มีการกำหนดจำนวนเต็มก่อนหน้านี้ และเข้าถึงและแสดงค่าบนคอนโซล
public class BooleanValues { public static void main(String[] args) { boolean my_input_1, my_input_2, my_input_3, my_result; my_input_1 = true; my_input_2 = true; my_input_3 = false; System.out.println("The three boolean values are defined as " +my_input_1 +" , " +my_input_2 + " and " +my_input_3); if(my_input_1) { my_result = my_input_2 || my_input_3; } else { my_result = my_input_2 && my_input_3; } if(my_result) { System.out.println("Two of the three variables are true"); } else { System.out.println("Two of the three variables are false"); } } }
ผลลัพธ์
The three boolean values are defined as true , true and false Two of the three variables are true