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

Java使用其他类getter作为switch表达式时语句被跳过问题

问题根因

核心问题是你创建了多个互不关联的InputRequests实例,不同实例的成员变量是独立存储的:

  • main方法中创建的input实例调用了loginChoice()接收了用户输入,所以最后打印的input.getLoginRole()是你输入的有效值
  • Menus类的loginChoiceCase()方法内部重新new InputRequests()创建了全新的inp实例,该实例从未调用过输入方法,loginRole是int类型的默认初始值0,你的switch分支没有匹配0的case,因此直接跳过执行。

修复方案

方案1(优先推荐):传入已完成赋值的InputRequests实例

修改Menus类的方法,增加入参接收外部的InputRequests实例,避免重复创建新对象:

public class Menus {
    // 新增InputRequests类型入参
    public void loginChoiceCase(InputRequests inp) {
        switch (inp.getLoginRole()) {
            case 1 -> System.out.println("test");
            case 2 -> System.out.println("tested");
            case 3 -> System.exit(1);
            // 建议补充default分支,方便排查未匹配场景
            default -> System.out.println("未匹配分支,当前输入值为:" + inp.getLoginRole());
        }
    }
}

修改main方法的调用逻辑,把已经完成输入的实例传入方法:

public class Main {
    public static void main(String[] args) {
        Printblocks print = new Printblocks();
        InputRequests input = new InputRequests();
        Menus menu = new Menus();
        print.firstMenu();
        input.loginChoice();
        // 传入已赋值的实例
        menu.loginChoiceCase(input);
        System.out.println(input.getLoginRole());
    }
}

方案2(适合全局唯一角色场景):设置静态变量

如果程序运行期间只会存在一个登录角色,可以将loginRole和对应getter设为静态,所有实例共享同一个值:

public class InputRequests {
    // 改为静态变量,全局共享
    public static int loginRole;

    public void loginChoice(){
        Scanner login = new Scanner(System.in);
        loginRole = login.nextInt();
    }
    // 改为静态方法
    public static int getLoginRole() {
        return loginRole;
    }
} 

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 00:36:03