I want to create an array of objects as mentioned in this answer:
Creating an array of objects in Java
i.e initialize one at a time like
A[] a = new A[4];
a[0] = new A();
My class definition:
public class Question {
private int mAnswer;
private String mQuestion;
private String[] mOptions;
public Question(String question, int answer, String[] option){
mQuestion = question;
mAnswer = answer;
mOptions = option;
}
public int getmAnswer() {
return mAnswer;
}
public String getmQuestion() {
return mQuestion;
}
public String[] getmOptions() {
return mOptions;
}
};
My Java Activity:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import static android.R.attr.x;
public class HomeActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
}
String[] options1 = {"ABCD", "EFGH", "IJKL", "MNOP"};
String[] options2 = {"Bangalore", "Delhi", "Mumbai", "Pune"};
String[] options3 = {"Business", "Work", "Nothing", "Study"};
Question[] ques = new Question[3];
ques[0] = new Question("What is your name?", 2, options1);
ques[1] = new Question("Where are you from?", 3, options2);
ques[2] = new Question("What do you do?", 4, options3);
}
But the initializations :
ques[0] = new Question("What is your name?", 2, options1);
ques[1] = new Question("Where are you from?", 3, options2);
ques[2] = new Question("What do you do?", 4, options3);
give me an error. These lines get underlined RED giving me all of the following errors for each line:
-Identifier expected
-Invalid method declaration; return type required
-Missing method body, or declare abstract
-Parameter expected
-Unexpected token
-Unknown class: 'ques'
I have no errors when I use:
Question[] ques = new Question[]{new Question("What is your Name?", 2, options1), new Question("Where are you from?", 3, options2),new Question("What do you do?", 4, options3)};
Why is that happening?
I have no idea where I am going wrong. I'm a beginner in Android and Java. Any help would be appreciated. Thanks.