3.5 Compund Boolean expressions

Nested conditional statements

definition: if statements within other if statements

public class Main {
    public static void main(String[] args) {
        int age = 20;
        boolean isStudent = true;

        // Outer if-else block
        if (age >= 18) {
            // Nested if-else block inside the first condition
            if (isStudent) {
                System.out.println("You are an adult and a student.");
            } else {
                System.out.println("You are an adult.");
            }
        } else {
            System.out.println("You are not an adult.");
        }
    }
}

Simple Example of a Nested Conditional Statement

Let’s look at a very basic example of a nested conditional statement using if-else blocks.

Scenario:

We want to check if a person is an adult and, if they are, we want to know if they are also a student.

Compound Conditional Statement

A compound conditional statement is when two or more conditions are combined into a single if statement using logical operators like && (AND), || (OR), or ! (NOT). This allows us to check multiple conditions at once without needing to nest if statements.

Logical Operators:

  • && (AND): True if both conditions are true.
  • || (OR): True if at least one condition is true.
  • ! (NOT): Reverses the result of a condition (true becomes false, and false becomes true).

Example of a Compound Conditional Statement

Let’s say we want to check if a person is an adult and a student at the same time. Instead of using a nested if statement, we can use a compound conditional statement.

public class Main {
    public static void main(String[] args) {
        int age = 20;
        boolean isStudent = true;

        // Compound conditional using && (AND)
        if (age >= 18 && isStudent) {
            System.out.println("You are an adult and a student.");
        } else {
            System.out.println("Either you are not an adult, or you are not a student.");
        }
    }
}

common mistake: Dangling else

- Java does not care about indentation
- else always belongs to the CLOSEST if
- curly braces can be use to format else so it belongs to the FIRST 'if'

Popcorn hack

  • explain the purpose of this algorithm, and what each if condition is used for
  • what would be output if input is
    • age 20
    • anual income 1500
    • student status: yes

Explanation of the Algorithm The algorithm in the code example checkMembershipEligibility() is designed to check a user’s eligibility for various types of memberships and discounts based on their age, annual income, and student status. Here’s the breakdown of what each part of the code does:

Inputs:

Age (age): This input is collected as an integer value from the user. Annual income (income): This input is collected as a floating-point number. Student status (isStudent): This input checks if the user enters “yes” or “no” and converts it into a boolean (true for “yes”, false for “no”). Results Array:

The algorithm initializes an empty array called results to store the different membership and discount qualifications. Conditions for Memberships and Discounts:

Basic Membership: The user qualifies if their age is 18 or older and their income is at least $20,000. Premium Membership: The user qualifies if their age is 25 or older and their income is at least $50,000. Student Discount: The user qualifies for this if they are a student (isStudent is true). Senior Discount: The user qualifies if they are 65 or older. Default Message:

If none of the conditions are met (the results array is empty), the default message “You do not qualify for any memberships or discounts.” is pushed into the array. Output:

All results in the results array are printed to the console. What would the output be for: Age: 20 Annual Income: 1500 Student Status: Yes Algorithm Analysis: Basic Membership: age >= 18 is true, but income >= 20000 is false, so the user does not qualify for Basic Membership. Premium Membership: age >= 25 is false, so the user does not qualify for Premium Membership. Student Discount: The user is a student (isStudent is true), so they do qualify for a Student Discount. Senior Discount: age >= 65 is false, so the user does not qualify for a Senior Discount.

function checkMembershipEligibility() { // Get user input let age = parseInt(prompt(“Enter your age:”)); // Age input let income = parseFloat(prompt(“Enter your annual income:”)); // Annual income input let isStudent = prompt(“Are you a student? (yes/no):”).toLowerCase() === ‘yes’; // Student status input

// Initialize an empty array to hold results
let results = [];

// Check eligibility for different memberships

// Basic Membership
if (age >= 18 && income >= 20000) {
    results.push("You qualify for Basic Membership.");
}

// Premium Membership
if (age >= 25 && income >= 50000) {
    results.push("You qualify for Premium Membership.");
}

// Student Discount
if (isStudent) {
    results.push("You are eligible for a Student Discount.");
}

// Senior Discount
if (age >= 65) {
    results.push("You qualify for a Senior Discount.");
}

// If no eligibility, provide a default message
if (results.length === 0) {
    results.push("You do not qualify for any memberships or discounts.");
}

// Output all results
results.forEach(result => console.log(result)); }

// Call the function to execute checkMembershipEligibility();

Popcorn Hack #2

  • Write a program that checks if a person can get a discount based on their age and student status. You can define your own discount criteria! Use compound conditionals to determine the output.
public class Main {
    public static void main(String[] args) {
        int age = 30; // Change this value for testing
        boolean isStudent = true; // Change this value for testing

        // Your compound conditional logic here
    }
}