【发布时间】:2018-06-22 18:47:07
【问题描述】:
我想创建这个答案中提到的对象数组:
Creating an array of objects in Java
即一次初始化一个
A[] a = new A[4];
a[0] = new A();
我的班级定义:
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;
}
};
我的 Java 活动:
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);
}
但是初始化:
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);
给我一个错误。这些行带有红色下划线,为我提供了每一行的以下所有错误:
-需要标识符
-无效的方法声明;需要返回类型
-缺少方法体,或声明抽象
-预期参数
-意外的令牌
-未知类:“问题”
我使用时没有错误:
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)};
为什么会这样?
我不知道我哪里出错了。我是 Android 和 Java 的初学者。 任何帮助,将不胜感激。 谢谢。
【问题讨论】:
-
您有语法错误。在 setContentView 之后关闭函数。在 ques[2] = .. 之后放置右括号
-
一般来说,如果你要将对象放入一个列表中,你应该使用 ArrayList 而不是你所展示的静态数组。
标签: java android arrays object initialization