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

Java报错:Drink类构造器无法匹配给定参数,求解决方案

Java构造器错误及代码修复方案

报错详情

constructor Drink in class Drink cannot be applied to given types;

Drink firstOrder=new Drink();
                         ^
  required: String,double
  found: no arguments
  reason: actual and formal argument lists differ in length

代码问题梳理

  • 构造器调用不匹配:Drink类自定义了带String和double参数的构造器,Java不会再自动生成无参构造器,所有创建Drink对象的地方必须传入指定参数。
  • 成员变量访问逻辑错误:Store类里错误地试图给Drink对象的orderOne赋值,实际上orderOne是Store的私有成员,且Drink的name、cost是私有变量,不能直接外部赋值,应通过构造器完成初始化。
  • main方法语法错误:Coffe未加引号会被识别为变量而非字符串;重复定义了d2变量。
  • 类职责混淆:Drink类的printDrink和getCost方法错误依赖Store对象,还引用了不存在的变量。Drink只需要管理单个饮品的信息,总成本计算和订单打印应该由持有两个Drink实例的Store类负责。

修复后的代码

Store类

public class Store {
    private Drink orderOne;
    private Drink orderTwo;

    // 通过构造器初始化两个饮品订单
    public Store(String name1, double cost1, String name2, double cost2) {
        orderOne = new Drink(name1, cost1);
        orderTwo = new Drink(name2, cost2);
    }

    public static void main(String args[]) {
        // 修正字符串引号问题,移除重复变量定义
        Store s1 = new Store("Lemon Tea", 5.25, "Coffee", 3.99);
        s1.printReport();
    }

    // 打印订单详情并计算总成本
    void printReport() {
        System.out.println("Drink order one is " + orderOne.getName() + " ($" + orderOne.getCost() + ")");
        System.out.println("Drink order two is " + orderTwo.getName() + " ($" + orderTwo.getCost() + ")");
        double totalCost = orderOne.getCost() + orderTwo.getCost();
        System.out.println("Total Cost : $ " + totalCost);
    }
}

Drink类

class Drink {
    private String name;
    private double cost;

    // 自定义构造器初始化饮品信息
    public Drink(String name, double cost) {
        this.name = name;
        this.cost = cost;
    }

    // 提供getter方法让外部访问私有变量
    public String getName() {
        return name;
    }

    public double getCost() {
        return cost;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 17:27:24