0

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 has a constructor of type Address() and of Address(string, string, string, string, string, string, string, string, string)

Now this given code does not work inside the main TestAddress class, it gives an error on the line where I'm declaring adrsarr

- Syntax error on token ";", { expected after this token

But if I put it inside a function like buildArr(), then it compiles flawlessly, no errors.

Any idea what's happening? How am I supposed to initialize an object array without making a function?

4

2 回答 2

2

现在这个给定的代码在主 TestAddress 类中不起作用,它在我声明 adrsarr 的行上给出了一个错误

您不能在方法、构造函数或初始化块之外填充数组

 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
        }
  }
于 2012-11-18T11:05:24.807 回答
-1

使用 Array Initializer 代替初始化赋值语句。

Address[] add = { new Address(), new Adress(), new Adress() }; 

数组初始化器只能在声明中使用或作为数组创建表达式的一部分(请参阅Java 语言规范 - 第 10.6 章“数组初始化器” )

于 2012-11-18T11:10:18.483 回答