Trong bài viết này, chúng ta sẽ tìm hiểu cách kiểm tra xem hai trong ba biến boolean có phải là true hay không. Biến boolean chỉ chứa giá trị true hoặc false.
Dưới đây là minh họa:
Đầu vào
Giả sử đầu vào là:
Đầu vào: true, true, false
Đầu ra
Kết quả mong đợi:
Kết quả: Hai trong ba biến là true
Thuật toán
Bước 1 - BẮT ĐẦU Bước 2 - Khai báo 4 giá trị boolean: my_input_1, my_input_2, my_input_3, my_result Bước 3 - Đọc giá trị từ người dùng hoặc định nghĩa trước Bước 4 - Sử dụng điều kiện if-else, so sánh hai trong ba giá trị mỗi lần dùng toán tử AND. Bước 5 - Hiển thị kết quả Bước 6 – DỪNG
Ví dụ 1: Nhập từ bàn phím
Người dùng nhập giá trị dựa trên lời nhắc. Thử trực tiếp trong coding ground.
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");
}
}
}
Đầu ra
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
Ví dụ 2: Giá trị định nghĩa trước
Ba giá trị boolean đã được định nghĩa trước.
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");
}
}
}
Đầu ra
The three boolean values are defined as true, true and false Two of the three variables are true