如何初始化数组的对象?

时间:2015-11-11 15:41:44

标签: java arrays

我有一个包含10个对象的数组,我想为数组初始化它们。

find dirname -name '*.gz' -print0 | xargs -0 -L 1 gzip -c -d -r

但是我遇到了很多错误,例如:

  

ReservationGUI.java:31:错误:']'预期

     

ReservationGUI.java:31:错误:非法启动类型

     

ReservationGUI.java:31:错误:';'预期

     

ReservationGUI.java:31:错误:预期

其中有100个。

3 个答案:

答案 0 :(得分:5)

这里有一些不同的错误。

private Flight[] flight = new Flight[10];

private开始,我假设这不在方法中。如果它在方法内,请删除private。否则,其他一切都应该进入你的构造函数。您只能在方法之外进行变量声明。

flight[1] = new Flight("AA102", "Lincolin", Jacksonville, 612.08, 22 6);

你需要引用"杰克逊维尔",因为它应该是String。您在22

之后也错过了逗号
flight{5} = new Flight("AA106", "Seattle", "Dallas" 326.14, 22, 6);

你在这一行(以及其他一些人)上使用了错误的括号。它应该是flight[5],而不是flight{5}[]用于索引数组。在" Dallas"。

之后,你也错过了一个逗号

这是更正后的版本:

private Flight[] flight = new Flight[10];

public YourClassName(){
    flight[0] = new Flight("AA101", "Boston",       "Sacremento",   421.33, 22, 6);
    flight[1] = new Flight("AA102", "Lincolin",     "Jacksonville", 612.08, 22, 6);
    flight[2] = new Flight("AA103", "Rochester",    "Columbia",     510.83, 22, 6);
    flight[3] = new Flight("AA104", "Boise",        "Aspen",        411.12, 22, 6);
    flight[4] = new Flight("AA105", "Fort Collins", "Louiseville",  654.22, 22, 6);
    flight[5] = new Flight("AA106", "Seattle",      "Dallas",       326.14, 22, 6);
    flight[6] = new Flight("AA107", "Phoenix",      "Little Rock",  974.22, 22, 6);
    flight[7] = new Flight("AA108", "Cheyenne",     "Louiseville",  521.43, 22, 6);
    flight[8] = new Flight("AA109", "Louiseville",  "Buffalo",      452.21, 22, 6);
    flight[9] = new Flight("AA100", "Anchorage",    "Tampa",        874.72, 22, 6);
}

或者,您可以将数组声明为一行,如下所示:

private Flight[] flight = {new Flight("AA101", "Boston", "Sacremento", 421.33, 22, 6),
                           new Flight("AA102", "Lincolin", "Jacksonville", 612.08, 22, 6),
                           /* The rest of your flights */
                           new Flight("AA100", "Anchorage", "Tampa", 874.72, 22, 6)};

这会将所有Flight声明和填充数组移动到数组本身的声明中。这使您可以初始化它而无需将其移动到方法中。有关详细信息,您可以read this。最终结果将是相同的,但它更简洁,更不容易出错。如果您决定要将数组的内容作为其他内容,它还可以让以后更容易更改。

答案 1 :(得分:0)

使用方括号代替5和6个元素的大括号

答案 2 :(得分:0)

你有很多拼写错误,并且所有编程语言都对拼写错误非常无情。

另一种方法:

private Flight[] flight = new Flight[] {
  new Flight("AA101", "Boston", "Sacremento", 421.33, 22, 6),
  new Flight("AA102", "Lincolin", "Jacksonville", 612.08, 22, 6),
  new Flight("AA103", "Rochester", "Columbia", 510.83, 22, 6),
  new Flight("AA104", "Boise", "Aspen", 411.12, 22, 6),
  new Flight("AA105", "Fort Collins", "Louiseville", 654.22, 22, 6),
  new Flight("AA106", "Seattle", "Dallas", 326.14, 22, 6),
  new Flight("AA107", "Phoenix", "Little Rock", 974.22, 22, 6),
  new Flight("AA108", "Cheyenne", "Louiseville", 521.43, 22, 6),
  new Flight("AA109", "Louiseville", "Buffalo", 452.21, 22, 6),
  new Flight("AA100", "Anchorage" , "Tampa", 874.72, 22, 6)
};