Week 8 · Objectives 第 8 周 · 学习目标 ← Back to Hub ← 返回主页

Control Structures I: Selection 控制结构一:选择结构

Learning Objectives 学习目标

  • Construct conditional selection structures using if and if-else statements.
  • Build multi-way branching programs using nested if-else and switch statements.
  • Implement real-world service pricing calculations based on user input constraints.
  • 使用 if 和 if-else 语句构建条件选择结构。
  • 使用嵌套的 if-else 和 switch 语句构建多路分支程序。
  • 根据用户输入限制实现实际的服务定价计算。
Bilingual Navigation:双语导航: Read and toggle languages using the globe button at the top. Test your understanding at the end of this page. 阅读并使用顶部的语言按钮切换中英文。在页面底部进行自我检测。

2 · Selection Structure Theory

By default, computer programs execute statements sequentially. A selection structure allows a program to evaluate logical conditions and decide which block of code to run: 默认情况下,计算机程序按顺序执行语句。选择结构允许程序评估逻辑条件并决定运行哪个代码块:

Single-Alternative (if)

Executes code block ONLY if condition is true. If false, skips it.仅当条件为真时执行代码块。如果为假,则跳过它。

Dual-Alternative (if-else)

Executes one block if true, and a different block if false.如果为真,执行一个块;如果为假,则执行另一个块。

Multi-Alternative

Chooses one block among multiple branches using nested structures or switch.使用嵌套结构或 switch,在多个分支中选择一个执行。

3 · The If and If-Else Statements

Java syntax uses if followed by boolean expression in parentheses. Complex choices are built by chaining else if: Java 语法使用 if 后跟括号中的布尔表达式。复杂的选择是通过链式 else if 构建的:

if (score >= 90) {{
    System.out.println("Grade: A");
}} else if (score >= 80) {{
    System.out.println("Grade: B");
}} else {{
    System.out.println("Grade: F");
}}

4 · The Switch Statement

The switch statement is an alternative to multi-way if-else when comparing a single variable against multiple literal integer, character, or string constant values. Always remember the break statement to prevent falling through into subsequent cases: 当将单个变量与多个整型、字符型或字符串常量值进行比较时,switch 语句是多路 if-else 的一种替代方案。请务必记住 break 语句,以防止“穿透”到后续的分支中:

switch (option) {{
    case 1:
        System.out.println("Option 1 selected");
        break; // Exits switch
    case 2:
        System.out.println("Option 2 selected");
        break;
    default:
        System.out.println("Invalid choice");
}}

Selection Logic Comparison选择逻辑比较

Selection Type选择类型 Condition Type条件类型 Supported Values支持的变量值 Best Used For最佳适用场景
if-else Relational / Range conditions关系/范围条件判断 All primitives, expressions, objects Range checks, complex conditions区间检查、多条件判断
switch Direct literal equality matches直接的字面量等值匹配 char, byte, short, int, String, enum Discrete menu options, specific values离散的菜单项、特定值的匹配

Applied Case Studies: Conditional Pricing Calculations应用案例研究:条件定价计算

We present three service calculation systems mapping selection logics. Click tabs to inspect. 我们展示了映射选择逻辑的三个服务计算系统。点击选项卡进行检查。

Kompas Cineplex Age-bounds PricingKompas Cineplex 区分年龄的票价计算

import java.util.Scanner;
public class CinemaTicket {{
    public static void main(String[] args) {{
        Scanner input = new Scanner(System.in);
        System.out.print("Enter customer age: ");
        int age = input.nextInt();
        double price;

        if (age < 12) {{
            price = 12.00;
        }} else if (age >= 60) {{
            price = 15.00;
        }} else {{
            price = 25.00;
        }}
        System.out.printf("Ticket Price: RM %.2f%n", price);
        input.close();
    }}
}}

Kompas Plaza Parking FeesKompas Plaza 停车费计算

import java.util.Scanner;
public class ParkingFee {{
    public static void main(String[] args) {{
        Scanner input = new Scanner(System.in);
        System.out.print("Enter hours parked: ");
        double hours = input.nextDouble();
        double fee;

        if (hours < 2.0) {{
            fee = 3.00;
        }} else if (hours <= 8.0) {{
            fee = 10.00;
        }} else {{
            fee = 20.00;
        }}
        System.out.printf("Total Parking Fee: RM %.2f%n", fee);
        input.close();
    }}
}}

Kompas Auto Rental Days CalculationsKompas Auto Rental 租赁天数费用计算

import java.util.Scanner;
public class CarRental {{
    public static void main(String[] args) {{
        Scanner input = new Scanner(System.in);
        System.out.print("Enter rental days: ");
        int days = input.nextInt();
        double dailyRate;

        if (days > 7) {{
            dailyRate = 100.00; // Long term discount rate
        }} else {{
            dailyRate = 120.00; // Standard rate
        }}
        double totalCost = days * dailyRate;
        System.out.printf("Daily Rate: RM %.2f%n", dailyRate);
        System.out.printf("Total Cost: RM %.2f%n", totalCost);
        input.close();
    }}
}}

Kompas Water Utility BillingKompas 水费服务账单

import java.util.Scanner;
public class WaterUtility {{
    public static void main(String[] args) {{
        Scanner input = new Scanner(System.in);
        System.out.println("Select account type:");
        System.out.println("1. Domestic (No discount)");
        System.out.println("2. Senior Citizen (20% discount)");
        System.out.println("3. Low Income (40% discount)");
        System.out.print("Choice (1-3): ");
        int choice = input.nextInt();
        
        final double BASE_RATE = 10.00;
        double bill = BASE_RATE;

        switch (choice) {{
            case 1:
                bill = BASE_RATE;
                System.out.println("Domestic Account");
                break;
            case 2:
                bill = BASE_RATE * (1.0 - 0.20); // Senior discount: RM 8.00
                System.out.println("Senior Citizen Account");
                break;
            case 3:
                bill = BASE_RATE * (1.0 - 0.40); // Low income discount: RM 6.00
                System.out.println("Low Income Account");
                break;
            default:
                System.out.println("Invalid choice. Standard Base applied.");
        }}
        System.out.printf("Final Bill Due: RM %.2f%n", bill);
        input.close();
    }}
}}

Check Your Understanding自我检测

Q1. In selection structures, a multi-way branch based on matches of a single variable is best written in Java as:在选择结构中,基于单个变量匹配的多路分支在 Java 中最好编写为:

Q2. What is the purpose of the break keyword inside switch statements?在 switch 语句中,break 关键字的作用是什么?

Q3. Analyze condition: days = 10; in Kompas Auto Rental. What is the calculated dailyRate?分析条件:Kompas Auto Rental 中的 days = 10;。计算出的 dailyRate 是多少?

Q4. In Kompas Water Utility Billing, what bill value is produced if choice = 2?在 Kompas 水费服务账单中,如果 choice = 2,会产生什么账单金额?