You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在不破坏if语句的前提下拆分嵌套switch语句?

如何将嵌套switch移到外部并保留原逻辑

要实现把boardType对应的switch移到duration的switch外部,同时保留原有if语句的逻辑,核心是提升变量作用域并通过条件判断控制外部switch的执行时机,具体实现如下:


关键改动思路

  1. 提升变量作用域:把原本在duration的case块内声明的guestAmount、boardType移到外部,确保后续代码能访问到这些变量。
  2. 标记前置条件:在duration的有效分支里,标记“时长有效”状态;当客人数量符合要求时,再标记“客人数量有效”状态并获取boardType的值。
  3. 外部触发switch:在switch(duration)结束后,通过判断前置条件是否全部满足,决定是否执行boardType的switch,确保只有在合法流程下才触发餐型判断。

修改后的完整代码

import java.util.Scanner;

public class BookingHandler {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        
        int duration = input.nextInt();
        // 提升变量到外部作用域,让后续代码可访问
        int guestAmount = 0;
        String boardType = "";
        boolean isDurationValid = false;
        boolean isGuestValid = false;

        switch (duration) {
            default -> System.out.println("You have not entered a valid number of nights.");
            case 2, 7, 14 -> {
                isDurationValid = true;
                System.out.print("How many guests are in your party? ");
                guestAmount = input.nextInt();

                if (guestAmount >= 1 && guestAmount <= 10) {
                    isGuestValid = true;
                    System.out.print("What type of board would you like (full, half, or self-catering)? ");
                    boardType = input.next();
                } else {
                    System.out.println("Sorry, you are only allowed 1 to 10 guests.");
                }
            }
        }

        // 移到外部的boardType switch,仅当前置条件满足时执行
        if (isDurationValid && isGuestValid) {
            switch (boardType) {
                case "full", "half", "self-catering" ->
                        System.out.println("Valid details entered - booking may proceed");
                default -> System.out.println("Sorry, we do not cater that type of board.");
            }
        }

        input.close();
    }
}

逻辑一致性说明

  • 当duration无效时,仅输出错误信息,不会触发后续餐型判断。
  • 当duration有效但客人数量超出范围时,输出客人数量错误,同样不会执行餐型判断。
  • 只有当duration和客人数量都符合要求时,才会执行boardType的switch判断,完全保留了原嵌套代码的逻辑。

如果不想用标记变量,也可以直接通过条件判断前置状态,写法更简洁:

if ((duration == 2 || duration == 7 || duration == 14) && guestAmount >= 1 && guestAmount <= 10) {
    switch (boardType) {
        case "full", "half", "self-catering" ->
                System.out.println("Valid details entered - booking may proceed");
        default -> System.out.println("Sorry, we do not cater that type of board.");
    }
}

内容的提问来源于stack exchange,提问作者Hamza Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 11:05:27