方法的编译器错误

时间:2012-04-29 21:32:52

标签: java compiler-construction

我在制作一个小程序时遇到了麻烦。基本上我有6个类。 1个主要类,4个子类,"扩展"主类和另一个运行程序的类。到目前为止,运行该程序的类已经布置好了:

public class ClassToRunProgram {

public void main(String[] args){

Class1 a = new Class1(0, "class1"); //I've created 1 main class (Class5) that 
Class2 b = new Class2(1, "class2"); //these 4 classes extend.
Class3 c = new Class3(2, "class3");
Class4 d = new Class4(3, "class4");

int randomNum = (int) (Math.random() *3);

Class5[] arrayForClasses = new Class5[]{a, b, c, d}; //since they're extending this
                                                    //class I want to make them into
                                                   //a single Array?


    String numberQuestion = JOptionPane.showInputDialog(null, 
"What question do you want to ask? \n 
Enter a number: \n 
1. First Question? \n 
2. Second Question? \n 
3. Third Question?");

int question = Integer.parseInt(numberQuestion); //not sure if this part is 
                                                //actually relevant at all??
                                               //Think it might be since I want to
                                              //use integers in my if statement below


if(question == 1){
    JOptionPane.showMessageDialog(null, "Blah blah"+arrayForClasses.getReturnValue()+" blah");
}

.getReturnValue()方法在所有类(1-5)中。我不确定这是否真的是我必须要做的。但我遇到的问题是,当我编译它时(即使它没有完成),它会引发一个"无法找到符号"错误消息" symbol:方法.getReturnValue()位置:变量arrayForClasses类型Class5 []"。我只是想知道我在哪里弄错了?

非常感谢任何帮助。

谢谢!

2 个答案:

答案 0 :(得分:2)

arrayForClasses是一个数组,您不能将方法添加到数组,只能添加到内部数组中的对象。您需要在数组中的对象上调用方法,而不是数组本身。像

这样的东西
arrayForClasses[0].getReturnValue()

现在,我说“类似”,因为我很难跟踪你想要做的事情,而且我有点担心将“getReturnValue()”方法放入许多不同的想法没有特定理由的课程。

答案 1 :(得分:1)

arrayForClasses是一个数组;它不是包含对象的类之一,因此它没有getReturnValue()方法

您需要访问数组的元素( Class5或其子类之一的对象),并在其上调用getReturnValue()

arrayForClasses[0].getReturnValue()

索引可以从0到3(总共4个元素),您可以使用其中任何一个。您甚至可以循环访问所有这些:

for (Class5 elem : arrayForClasses) { // cycles through each element in order
  elem.getReturnValue();
}