繁体   English   中英

创建一个对象数组是必要的

[英]Creating an array of objects help needed

我正在尝试制作一个对象数组。 我有两个类,主要和另一个类的方法。 我正在运行该程序的是TestTrivia,具有TestTrivia所有方法的类是Question。 这个类的构造函数是public Question(){question =“null”; answer =“null”; pointValue = 0; 我正在尝试做这样的事情Person personArray [] = new Person [5];

   for(int i=0; i< personArray.length; i++)
   {
    personArray[i] = new Person();
  }

所以我尝试过Question QuestionArray [] = new Question [5]; for(int i = 0; i <QuestionArray.length; i ++){QuestionArray [i] = new Question(); 我试图在两个类中使用它,主要和一个方法。 它应该进入主类正确吗? 我得到的错误是整个for语句加下划线并说:非法启动类型找不到符号符号:class i location:class triviagame.TriviaGame包QuestionArray不存在triviagame是包名,“TriviaGame”是类名, “问题”是另一个类名。

循环代码需要在main之类的方法中。

此外,如果它们不在同一个包中,则需要导入不在“当前”包中的类。 例如,如果Question在默认包中,则需要将其导入TriviaGame类。

package triviagame;

import Question;

public class TriviaGame {
    public static void main(String[] args) {
        System.out.println("Welcome to the New Age Trivia game");
        System.out.println("You will be asked five questions, let us begin");
        Question questionArray[] = new Question[5];
        for (int i = 0; i < questionArray.length; i++) {
            questionArray[i] = new Question();
        }
    }
}

如果Question类也在triviagame包中,则不需要导入。

您正在尝试在方法或构造函数或初始化程序块之外进行方法调用。 不要这样做,而是确保您的代码位于正确的位置,例如在main或其他方法中。

public class TriviaGame {

   public static void main(String[] args) 
   {
      System.out.println("Welcome to the New Age Trivia game");
      System.out.println("You will be asked five questions, let us begin");
   }

   // this code is sitting out in the middle of no-where
   Question questionArray[] = new Question[5];
   for(int i=0; i< questionArray.length; i++)
   {
     questionArray[i] = new Question();
   }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM