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

时间:2013-09-27 23:16:16

标签: 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());
}

这是主要的课程

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());
        }
    }
}

这里是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; }

}

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

3 个答案:

答案 0 :(得分:4)

这很容易,你在这里遗漏了一些东西:

volume.getVolume()

应为volume[i].getVolume()

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

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

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

答案 1 :(得分:3)

而不是

volume.getVolume()

使用

volume[i].getVolume()

您使用的是数组而不是数组的元素 - 并且数组没有getVolume()方法...这可以理解导致语法错误...

答案 2 :(得分:1)

volume是一个数组(Cylindar),因此它没有您的方法getVolume。您可能需要volume[i].getVolume,因为这是您在print语句的其余部分引用的cylindar对象。