我一直在为Comp Sci入门课程设计实验室,但遇到了以下问题:

按照说明,我必须拥有回答特定问题的所有方法(例如:问题5.9,方法是fourPointNine(),并且必须在main中由另一个类(Assignment6.main)调用。我的问题是main是静态的,我需要为该实验室调用的最终方法是非静态的,因此它将不允许我编译和运行。我遇到的三个错误与multiSphere(x)有关。具体错误是“无法静态引用类型Assignment6中的非静态方法“ multiSphere(double)”。”

public class Assignment6
{
public Sphere newSphere = new Sphere();
public Assignment6 A6 = new Assignment6();
public static int x;
public static void main(String[] args)
{
       x = 2 + (int)(Math.random() * ((10 - 2) + 1));
   multiSphere(x);

   x = 2 + (int)(Math.random() * ((10 - 2) + 1));
   multiSphere(x);

   x = 2 + (int)(Math.random() * ((10 - 2) + 1));
   multiSphere(x);
    }
    public void multiSphere(double diameter)
    {
    Sphere.inputDiameter(diameter);
    Sphere.volumeCalc(diameter);
    Sphere.surfaceAreaCalc(diameter);
    toString();
}
public String toString()
{
   return "The diameter of this sphere is " + Sphere.inputDiameter(x) + ", the volume      is " + Sphere.volumeCalc(x) + ", and the surface area is " + Sphere.surfaceAreaCalc(x) + ". ";
}


我的第二堂课叫做Sphere,看起来像这样:

public class Sphere
{
public Assignment6 newA6 = new Assignment6();
public static double volume;
public static double surfaceArea;
public static double inputDiameter(double diameter)
{
    return diameter;
}
public static double volumeCalc(double diameter)
{
    // Volume = (4.0/3.0)(pi)(r)^3
    volume = (4.0/3.0) * (Math.PI) * Math.pow((diameter/2.0), 3);
    return volume;
}
public static double surfaceAreaCalc(double diameter)
{
    // Surface area = (4)(pi)(r)^2
    surfaceArea = (4) * (Math.PI) * (Math.pow((diameter/2.0), 2));
    return surfaceArea;
}
}


我不确定如何在main方法中调用multiSphere(x),而不会遇到我遇到的错误。我感觉好像缺少了这么简单的东西。

最佳答案

这里有很多事情需要快速纠正-尤其是决赛即将到来。

首先,您需要了解Sphere类应该如何工作。 Sphere的每个实例都是自己的东西,并且知道如何做。 Sphere只需给出其直径(或半径)即可,并且可以确定其自身所需的所有信息。它可以计算其体积和表面积,并可以在toString中打印出来。

因此,您希望Sphere看起来像这样:

public class Sphere {
    public double diameter;

    public Sphere(double diameter) {
        this.diameter = diameter;
    }

    public double volume() {
        return (4.0 / 3.0) * (Math.PI) * Math.pow((diameter / 2.0), 3);
    }

    public double surfaceArea() {
        return (4) * (Math.PI) * (Math.pow((diameter / 2.0), 2));
    }

    public String toString()
    {
       return "The diameter of this sphere is " + diameter + ", the volume is " + volume() + ", and the surface area is " + surfaceArea() + ". ";
    }
}


注意Sphere如何具有构造函数,这就是我们创建Sphere的新实例的方式。我们只用直径来做。一旦有了它,Sphere的实例就可以完成Sphere的所有工作。

注意也没有static。我不知道你为什么如此爱static

您应该知道static任何东西都意味着该类的每个实例都共享它。这不适用于Sphere,因为每个实例都有自己的直径。并非一堆Sphere共享直径。有些直径可能相等,但它们仍然是自己的。就像您和我如何驾驶宾利汽车(一厢情愿)一样,它们在各个方面都相同,但它们仍然是两辆不同的汽车。当然,static事物不能访问非static事物,因为非static事物需要成为可能不可用的对象实例的一部分。

最后,在主类Assignment6中,您只需执行以下操作:

Sphere s = new Sphere(5);


创建直径为5的Sphere实例。现在,s可以通过toString告诉我们其体积,表面积和描述。

我实际上不确定您的任务是什么,但是希望这会对您有所帮助。

09-11 03:54
查看更多