3.5 + 3.6 Compund Boolean expressions + Equivalent Boolean Expressions

Nested conditional statements

definition: if statements within other if statements

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Get user input for age
        System.out.print("Enter your age: ");
        int age = scanner.nextInt();
        
        // Get user input for student status
        System.out.print("Are you a student? (yes/no): ");
        String studentResponse = scanner.next().toLowerCase();
        boolean isStudent = studentResponse.equals("yes");
        
        // Outer if-else block
        if (age < 18) {
            System.out.println("You are a minor.");
        } else {
            // Nested if-else block
            if (isStudent) {
                System.out.println("You are an adult student.");
            } else {
                System.out.println("You are an adult.");
            }
        }

        scanner.close();
    }
}

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
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();