方法的编译器错误

问题描述 投票:0回答:2

我正在制作的一个小程序遇到了问题。基本上我有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) 中。我不确定这是否真的是我必须做的。但我遇到的问题是,当我编译它时(即使它还没有完成),它会抛出“CANNOT FIND SYMBOL”错误,并显示消息“symbol:method .getReturnValue()location:variable arrayForClasses type Class5 []” 。我只是想知道我哪里出了问题?

非常感谢任何帮助。

谢谢!

java
2个回答
2
投票

arrayForClasses
是一个数组,你不能向数组添加方法,只能向数组内部的对象添加方法。您需要调用数组中对象的方法,而不是数组本身。所以类似

arrayForClasses[0].getReturnValue()

现在,我说“类似的东西”是因为我很难理解你想要做的事情,并且我有点担心将“getReturnValue()”方法放入许多不同的类中而不需要这样做的想法这样做的具体原因。


1
投票

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

您需要访问数组的一个元素(

Class5
或其子类之一的对象),并对其调用
getReturnValue()

arrayForClasses[0].getReturnValue()

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

for (Class5 elem : arrayForClasses) { // cycles through each element in order
  elem.getReturnValue();
}
© www.soinside.com 2019 - 2024. All rights reserved.