ในบทความนี้ เราจะเรียนรู้วิธีตรวจสอบว่ามีตัวแปร Boolean เป็น true อยู่ 2 ใน 3 ตัวในภาษา Java ตัวแปร Boolean เก็บค่าได้แค่ true หรือ false
ตัวอย่างการทำงาน
อินพุต:
Input: true, true, false
เอาต์พุต:
Result: Two of the three variables are true
อัลกอริทึม
- เริ่มต้นโปรแกรม
- ประกาศตัวแปร boolean 4 ตัว:
my_input_1,my_input_2,my_input_3,my_result - รับค่าจากผู้ใช้ หรือกำหนดค่าไว้ล่วงหน้า
- ใช้เงื่อนไข if-else: ถ้า input_1 เป็น true ตรวจสอบ input_2 หรือ input_3 (OR) มิฉะนั้น ตรวจสอบ input_2 และ input_3 (AND)
- แสดงผลลัพธ์
- จบโปรแกรม
ตัวอย่างที่ 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");
}
}
}
ตัวอย่างที่ 2: กำหนดค่าไว้ล่วงหน้า
public class BooleanValues {
public static void main(String[] args) {
boolean my_input_1 = true, my_input_2 = true, my_input_3 = false, my_result;
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");
}
}
}
ตรรกะ: ถ้าตัวแรกเป็น true ต้องการอีกตัวใดตัวหนึ่งเป็น true (OR) แต่ถ้าตัวแรกเป็น false ต้องการทั้งสองตัวที่เหลือเป็น true (AND)