简体   繁体   中英

Creating an array of objects help needed

I am trying to make an array of objects. I have Two classes, the main and another class for the methods. The one i am running the program in is TestTrivia, the class with all the methods for TestTrivia is Question. Constructor for this class is public Question() { question = "null"; answer = "null"; pointValue = 0; } i am trying to do something like this Person personArray[] = new Person[5];

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

So i have tried Question QuestionArray[] = new Question[5]; for(int i=0; i< QuestionArray.length; i++) { QuestionArray[i] = new Question(); } I have tried to use it in both classes, the main and the one full of methods. It should go into the main class correct? The error i am getting is the whole for statement is underlined and says: illegal start type cannot find symbol symbol: class i location: class triviagame.TriviaGame package QuestionArray does not exist triviagame is the package name, "TriviaGame" is the class name, "Question" is another class name.

The loop code needs to be within a method, like main .

Also, if they are not in the same package, you will need to import classes not in the "current" package. For example, if Question is in the default package, it will need to be imported into the TriviaGame class.

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();
        }
    }
}

If the Question class is in the triviagame package as well, the import is unnecessary.

You're trying to make methods calls outside of a method or constructor or initializer block. Don't do this, but instead make sure your code is in the proper location such as in the main or another method.

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();
   }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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