作业 Java - 语法错误,无法调用数组中的方法。

use*_*785 3 java class getter-setter

我有一个家庭作业,我从用户那里获取圆柱的半径和高度的输入,然后返回体积。我认为我已经完成了大部分工作,但无法将它们整合在一起。当我尝试将其全部打印出来时出现语法错误。这是打印线

for (int i = 0; i < volume.length; i++)
{
    System.out.println("for Radius of:" + volume[i].getRadius() + " and Height of:" + volume[i].getHeight() + " the Volume is:" + volume.getVolume());
}
Run Code Online (Sandbox Code Playgroud)

这是主类

import javax.swing.*;

//Driver class
public class CylinderTest
{

    public static void main(String[] args)
    {

        Cylinder[] volume = new Cylinder[3];
        for (int counter = 0; counter < volume.length; counter++)
        {
            double radius = Double.parseDouble(JOptionPane
                    .showInputDialog("Enter the radius"));
            double height = Double.parseDouble(JOptionPane
                    .showInputDialog("Enter the height"));
            volume[counter] = new Cylinder(radius, height);
        }

        for (int i = 0; i < volume.length; i++)
        {
            System.out.println("for Radius of:" + volume[i].getRadius() + " and Height of:" + volume[i].getHeight() + " the Volume is:" + volume.getVolume());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是 Cylinder 类

public class Cylinder
{
    // variables
    public static final double PI = 3.14159;
    private double radius, height, volume;

    // constructor
    public Cylinder(double radius, double height)
    {
        this.radius = radius;
        this.height = height;
        this.volume = volume;
    }

    // default constructor
    public Cylinder()
    {this(0, 0);}

    // accessors and mutators (getters and setters)
    public double getRadius()
    {return radius;}

    private void setRadius(double radius)
    {this.radius = radius;}

    public double getHeight()
    {return height;}

    private void setHeight(double height)
    {this.height = height;}

    public double getVolume()
    {return volume;}

    // Volume method to compute the volume of the cylinder
    public double volume()
    {return PI * radius * radius * height;}

    public String toString()
    {return volume + "\t" + radius + "\t" + height; }

}
Run Code Online (Sandbox Code Playgroud)

我正在尝试从 Cylinder 类 getVolume getter 中获取音量。

Sim*_*erg 5

这很容易,你在这里错过了一些东西:

volume.getVolume()

应该 volume[i].getVolume()

volume是数组,volume[i]而是你的Cylinder类的一个实例。

作为旁注,您可以使用Math.PI已经定义的(并且更准确),而不是在常量中定义 PI 。

更新的答案:在您的 Cylinder 类中,您将volume变量初始化为 0。我建议您删除volume变量和getVolume方法。而不是调用getVolume方法,你应该调用volume()方法。计算体积非常快,您不需要将其存储为类中的变量。