问题描述:

I got a problem with a question.

Question: an Array instance variable called people has been set up by the line:

public Person[] people;

Write the line that will initialise/instantiate it to take 100 objects of type Person.

My answer:

 public Person[] people;

double []people = new Person [100];`

The error that I am getting is this:

 Main.java:8: illegal start of expression

public Person[] people;

What can I do to solve this problem?

网友答案:

public is keyword for definition method or attribute visibility in a class. If you are using only variable then it is without this keyword. So it should be Person[] people;.

Also I think you have a mistake in double []people = new Person [100]; It should be people = new Person [100]; but this is not initialization of 100 objects but only 1 array of 100 references to 100 NULLs. You have to use a for cycle to call 100x people[i] = new People();

网友答案:

This should be outside of your main method, within the class:

public Person[] people;

You can then initialize it without redeclaration:

people = new Person[100];
网友答案:

Since this is written in main, the public is unecessary, so your code can be simplified to:

Person[] people;
people = new Person[100];
相关阅读:
Top