tags:

views:

260

answers:

6

i am initializing an array data like:

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};
    }

}

NB points an error at the line data[10] = {10,20,30,40,50,60,71,80,90,91};

i cudn't get wat it is? any suggestions.

+5  A: 

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

Dean Povey
+1. You have an extra opening brace. One can also write: data[0] = 10; data[1] = 20; .... after int data[] = new int[10], but it is too much code and it will end up doing the same thing.
Hamish Grubijan
Thanks. Had already caught that and done an edit.
Dean Povey
A: 

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

schubySteve
-1 - You are just guessing, aren't you :-)
Stephen C
it did show the same error
chatty
+10  A: 
 data[10] = {10,20,30,40,50,60,71,80,90,91};

The above is not correct(the syntax). This means you are assigning the entire array to data[10] which can hold just an element.

If you want to initialize an array try this:

int data[] = new int[] {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 };

Even if you correct the syntax, accessing data[10] is still incorrect(You can only access data[0] to data[9]). Accessing data[10] will throw an AIOB(Array Index Out of Bounds) Exception.

Prasoon Saurav
Actually, the primary reason it is incorrect is that it is a syntax error! The AIOB would only happen if the syntax was acceptable.
Stephen C
Yeah,I've edited my post. Thanks :)
Prasoon Saurav
A: 

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;
fastcodejava
Edited to fix runtime ArrayIndexOutOfBounds exception
Stephen C
A: 

When you create an array of size 10 it allocated 10 slots but from 0 to 9. This for loop might help you see that a little better.

public class Array {
    int data[] = new int[10]; 
    /** Creates a new instance of Array */
    public Array() {
        for(int i = 0; i < data.length; i++) {
            data[i] = i*10;
        }
    }
}
Bernie Perez
A: 

maybe you want to use

int[] data

instead of

int data[]

they are both valid, but the second version is easier to read.

morsch