TestAddress.java
Address[] adrsarr = new Address[5];
adrsarr[0] = new Address("B402", "3", "42", "Behind Sector 9",
"New Delhi", "Delhi", "Delhi", "India", "232113");
adrsarr[1] = new Address("B1", "2", "61", "Bb Road 2", "Mumbai",
"Mumbai", "Maharashtra", "India", "1213");
adrsarr[2] = new Address("AH2", "325", "98", "BPGC", "Goa", "Goa",
"Goa", "India", "403726");
adrsarr[3] = new Address("a222", "2", "81", "Sector market",
"New Delhi", "Delhi", "Delhi", "India", "11a001");
Address.java 有一个 Address()
类型和 Address(string, string, string, string, string, string, string, string, string)
类型的构造函数
现在这个给定的代码在主 TestAddress 类中不起作用,它在我声明 adrsarr 的行上给出了错误
- Syntax error on token ";", { expected after this token
但是如果我将它放入像 buildArr() 这样的函数中,那么它可以完美编译,没有错误。
知道发生了什么吗?我应该如何在不创建函数的情况下初始化对象数组?
最佳答案
Now this given code does not work inside the main TestAddress class, it gives an error on the line where I'm declaring adrsarr
您不能在方法、构造函数或初始化 block 之外填充数组。
public class Country {
Address[] add = new Address[3];
add[0] = new Address();// this would not **compile**, put it inside a constructor /method.
{
this.add[0] = new Address();// populating inside an init block, works fine
}
public country() {
this.add[0] = new Address(); //populating inside a constructor, works fine
}
public void method(){
this.add[0] = new Address();//populating inside a method, works fine
}
}
关于java - 无法理解有关对象数组的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13439472/