class example{
int[] quiz = new int[] { 10 , 20 }; //location 1
public static void main(String[] args) {
int[] test = new int[2]; // location 2
test[0] = 2;
test[1] = 3;
// other code
}
Run Code Online (Sandbox Code Playgroud)
上面的代码运行正常.但是,下面的代码会导致错误.我的错误推理是因为quiz在方法之外声明它需要立即初始化.但是我不确定这是否是正确的解释.
class example{
int[] quiz = new int[2]; //location of error
quiz[0] = 10;
quiz[1] = 20;
public static void main(String[] args) {
int[] test = new int[2]; // location 2
test[0] = 2;
test[1] = 3;
//other code
}
Run Code Online (Sandbox Code Playgroud)
你需要一个初始化块来做第二种方式,
int[] quiz = new int[2];
{
quiz[0] = 10;
quiz[1] = 20;
}
Run Code Online (Sandbox Code Playgroud)