使用数组创建的对象,无法调用它的方法!!为什么?

时间:2011-08-24 14:25:38

标签: java

我创建了2个源代码文件, Shirt.java ShirtTestArray.java

我遇到的问题是,每当我尝试访问displayShirtInformation()方法时,我都无法做到这一点..并且出现错误类,接口或枚举 < / p>

下面给出了2个源文件 -

Shirt.java -

public class Shirt {

  public int shirtID = 0; // Default ID for the shirt
  public String description = "-description required-"; // default

  // The color codes are R=Red, B=Blue, G=Green, U=Unset
  public char colorCode = 'U';
  public double price = 0.0; // Default price for all shirts
  public int quantityInStock = 0; // Default quantity for all shirts

  public Shirt() {
  }

  public Shirt(int ID, String d, char c, double p, int q) {
    shirtID = ID;
    description = d;
    colorCode = c;
    price = p;
    quantityInStock = q;
  }

  // This method displays the values for an item
  public void displayShirtInformation() {

    System.out.println("Shirt ID: " + shirtID);
    System.out.println("Shirt description:" + description);
    System.out.println("Color Code: " + colorCode);
    System.out.println("Shirt price: " + price);
    System.out.println("Quantity in stock: " + quantityInStock);

  } // end of display method
} // end of class

ShirtTestArray.java -

public void  ShirtTestArray{
  public static void main(String [] args) {
    Shirt [] shirtArray={new Shirt (1,"blue",'b',76.67,4),new Shirt(2,"green",'g',98.79,1),
    new Shirt(3,"green",'g',34.78,90)};

    shirtArray[0].displayShirtInformation();
    shirtArray[1].displayShirtInformation();
    shirtArray[2].displayShirtInformation();

  }
}

3 个答案:

答案 0 :(得分:9)

第二个类应声明为class,而不是void:

public class ShirtTestArray{
       ^
    public static void main(String [] args){
    Shirt [] shirtArray={new Shirt

(1,"blue",'b',76.67,4),new Shirt(2,"green",'g',98.79,1),
    new Shirt(3,"green",'g',34.78,90)};



       shirtArray[0].displayShirtInformation();
       shirtArray[1].displayShirtInformation();
       shirtArray[2].displayShirtInformation();

    }

}

答案 1 :(得分:0)

你给了ShirtTestArray一个返回定义,说它应该是一个方法,它应该是一个类。

将'void'替换为'class',你应该滚动。

答案 2 :(得分:0)

语法错误为public void ShirtTestArray{而非public class ShirtTestArray{。 干杯:)