有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Tester类构造函数错误

这是我必须回答的家庭作业问题:实现一个类SodaCan,其构造函数接收高度和直径或汽水罐。提供方法getVolumegetSurfaceArea。提供一个测试类的SodaCanTester

这是我为SodaCan类编写的代码

public class SodaCan
{
    private double Height;
    private double Radius;

    public SodaCan(double h, double d) {
        Height = h;
        Radius = d/2;
    }

    public double getVolume()
    {
        return Math.PI * Height * Math.pow(Radius, 2);
    }

    public double getSurfaceArea()
    {
        return (2 * Math.PI * Radius * Height) + 
        (2 * Math.PI * Math.pow(Radius, 2));
    }   
}

这是我为SodaCanTester类编写的代码

public class SodaCanTester
{
    public static void main(String[] args)
    {
       SodaCan cylinder = new SodaCan();
       cylinder.enterHeight(5);
       cylinder.enterRadius(8);
       System.out.println("Volume: " + getVolume());
       System.out.println("Expected Volume: 1005.31");
       System.out.println("Surface Area: " + getSurfaceArea());
       System.out.println("Expected Surface Area: 653.45");
    }
}

当我试图编译tester类时,构造函数出现了一个错误:

SodaCan cylinder = new SodaCan();

也就是说:

"constructor SodaCan in class SodaCan cannot be applied to given types".

我做错了什么,我该如何解决


共 (1) 个答案

  1. # 1 楼答案

    因为,您的类中有args构造函数SodaCan

    public SodaCan(double h, double d) {
        Height = h;
        Radius = d/2;
    }
    

    如果你想让下面的代码正常工作,你需要显式地声明没有参数构造函数

    SodaCan cylinder = new SodaCan();
    

    编辑==

    你的代码应该是这样的

    public SodaCan(double h, double d) {
        Height = h;
        Radius = d/2;
    }
    
    public SodaCan(){}