我像这样初始化一个数组:

public class Array {

    int data[] = new int[10]; 
    /** Creates a new instance of Array */
    public Array() {
        data[10] = {10,20,30,40,50,60,71,80,90,91};
    }     
}

NetBeans在这一行指出一个错误:

data[10] = {10,20,30,40,50,60,71,80,90,91};

我怎么解决这个问题?


当前回答

也许这样会有用:

public class Array {

    int data[] = new int[10]; 
    /* Creates a new instance of Array */
    public Array() {
        data= {10,20,30,40,50,60,71,80,90,91};
    }
}

其他回答

您正在尝试将数组的第10个元素设置为数组try

data = new int[] {10,20,30,40,50,60,71,80,90,91};

FTFY

你可以:

int[] data = {10,20,30,40,50,60,71,80,90,91};

Try

data = new int[] {10,20,30,40,50,60,71,80,90,91 };

也许这样会有用:

public class Array {

    int data[] = new int[10]; 
    /* Creates a new instance of Array */
    public Array() {
        data= {10,20,30,40,50,60,71,80,90,91};
    }
}
data[10] = {10,20,30,40,50,60,71,80,90,91};

以上内容不正确(语法错误)。这意味着您将数组分配给数据[10],该数据只能容纳一个元素。

如果你想初始化一个数组,尝试使用数组初始化器:

int[] data = {10,20,30,40,50,60,71,80,90,91};

// or

int[] data;
data = new int[] {10,20,30,40,50,60,71,80,90,91};

请注意这两个声明之间的区别。当将一个新数组赋值给一个声明的变量时,必须使用new。

即使您纠正了语法,访问数据[10]仍然是不正确的(您只能访问数据[0]到数据[9],因为Java中的数组索引是基于0的)。访问数据[10]将抛出ArrayIndexOutOfBoundsException异常。