How to initialize an array in Java?

2018-12-31 09:49发布

I am initializing an array data like this :

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 points an error at the line

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

How can I solve the problem?

10条回答
弹指情弦暗扣
2楼-- · 2018-12-31 10:01

Rather than learning un-Official websites learn from oracle website

link follows:Click here

*You can find Initialization as well as declaration with full description *

int n; // size of array here 10
int[] a = new int[n];
for (int i = 0; i < a.length; i++)
{
    a[i] = Integer.parseInt(s.nextLine()); // using Scanner class
}

Input: 10//array size 10 20 30 40 50 60 71 80 90 91

Displaying data:

for (int i = 0; i < a.length; i++) 
{
    System.out.println(a[i] + " ");
}

Output: 10 20 30 40 50 60 71 80 90 91

查看更多
梦醉为红颜
3楼-- · 2018-12-31 10:05

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

查看更多
伤终究还是伤i
4楼-- · 2018-12-31 10:05

you are trying to set the 10th element of the array to the array try

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

FTFY

查看更多
不流泪的眼
5楼-- · 2018-12-31 10:06

You can do:

int[] data = {10,20,30,40,50,60,71,80,90,91};
查看更多
长期被迫恋爱
6楼-- · 2018-12-31 10:10

If you want to initialize an array in a constructor, you can't use those array initializer like.

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

Just change it to

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

You don't have to specify the size with data[10] = new int[] { 10,...,91} Just declare the property / field with int[] data; and initialize it like above. The corrected version of your code would look like the following:

public class Array {

    int[] data;

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

}

As you see the bracket are empty. There isn't any need to tell the size between the brackets, because the initialization and its size are specified by the count of the elements between the curly brackets.

查看更多
琉璃瓶的回忆
7楼-- · 2018-12-31 10:13

You cannot initialize an array like that. In addition to what others have suggested, you can do :

data[0] = 10;
data[1] = 20;
...
data[9] = 91;
查看更多
登录 后发表回答