2013-09-27 23 views
2

我有一個家庭作業,我從用戶那裏獲取圓柱半徑和高度的輸入,然後返回音量。我認爲我完成了大部分工作,但無法將它們結合在一起。當我嘗試全部打印時出現語法錯誤。這裏是打印線作業Java - 語法錯誤,無法調用數組中的方法。

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吸氣量。取而代之的

volume.getVolume() 

+2

嘗試添加確切的錯誤,我的IDE說:'不能在數組類型上調用getVolume()類型Cylinder []'它試圖從數組中獲取體積不是來自Cylinder實例。 – porfiriopartida

回答

4

這很容易,你錯過了這裏的東西:

volume.getVolume()

應該volume[i].getVolume()

volume是數組,而volume[i]是你Cylinder類的一個實例。

作爲一個方面說明,您可以使用Math.PI已定義(和更準確),而不是在常量中定義PI。

更新答案: 在你的Cylinder類,你初始化變量volume爲0,我建議你刪除volume變量和方法getVolume。而不是調用getVolume方法,您應該調用volume()方法。計算音量非常快,您不需要將其作爲變量存儲在課堂中。

+0

'而音量[我]是一個圓柱體實例*' – porfiriopartida

+0

@porfiriopartida的確是的。 –

+0

謝謝。不幸的是,現在將其返回0.0所有的答案 \t \t'對(INT I = 0; I user2802785

3

使用

volume[i].getVolume() 

您使用的陣列,而不是數組的元素的 - 和數組沒有一個getVolume()方法......這可理解地導致語法錯誤...

1

volume是一個數組(Cylindar),所以它沒有你的方法getVolume。您可能需要volume[i].getVolume,因爲這是您在打印語句的其餘部分引用的cylindar對象。