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

Java使用Interface对接多类时machine变量无法解析报错求助

问题原因
  • 变量作用域限制:你在if代码块内部定义的machine变量仅属于对应代码块的局部变量,离开代码块后就会失效,因此后续while循环中访问时会报machine cannot be resolved错误
  • 逻辑分支漏洞:当前两个if判断是独立关系,即使用户选了(G)umball machine,第一个if执行完后第二个if判断不通过,仍会触发else分支输出Invalid choice
解决方案

步骤1:定义公共售货机接口

先抽象出所有售货机的公共方法,定义为VendingMachine接口,让GumballMachine和SodaMachine都实现该接口:

public interface VendingMachine {
    // 出货
    String dispense();
    // 补货
    void refill(int amount);
    // 判空
    boolean isEmpty();
}

步骤2:修改main方法逻辑

将machine变量提到分支外声明,调整分支结构为if-else if避免逻辑错误,修改后代码如下:

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    // 分支外声明公共类型的变量,作用域覆盖整个main方法
    VendingMachine machine = null;

    out.println("(G)umball machine or (S)oda Machine: ");
    String choice1 = input.nextLine();
    
    // 调整为if-else if结构,避免逻辑冲突
    if(choice1.toLowerCase().equals("g")) {
        machine = new GumballMachine();
        machine.refill(0);
        machine.dispense();
        machine.isEmpty();
    } else if(choice1.toLowerCase().equals("s")) {
        machine = new SodaMachine();
        machine.refill(0);
        machine.dispense();
        machine.isEmpty();
    } else {
        out.println("Invalid choice");
        // 选择无效直接退出,避免后续空指针异常
        return;
    }
    
    while(true) {
        out.print("(V)end, (R)efill or (E)xit: ");
        String choice = input.nextLine();

        if(choice.toLowerCase().equals("v")) {
            out.println(machine.dispense());
        } else if (choice.toLowerCase().equals("r")) {
            out.print("Enter amount to refill: ");
            int amount = input.nextInt();
            input.nextLine();
            machine.refill(amount);
            out.println("Refilled...");
        } else if (choice.toLowerCase().equals("e")) {
            break;
        } else {
            out.println("Invalid choice");
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 16:54:02