JAVA - Problems initializing individual elements of an array
I'm very new to programming and I must be missing something here. The first section works. The second section blows up with an error. Why is that?
// this works
private static int[] test2 = {1,2,3};
// this is ok
private static int[] test1 = new int[3];
// these three lines do not work
// tooltip states ... "cannot find symbol. class test1. ']' expected."
test1[0] = 1;
test1[1] = 2;
test1[2] = 3开发者_JS百科;
From what you've posted, the lines
test1[0] = 1;
test1[1] = 2;
test1[2] = 3;
need to be inside a method or constructor. Looks like you have them outside at the class level. Lets say MyClass
is the name of your class. Add a constructor and put the three statements inside it:
MyClass {
test1[0] = 1;
test1[1] = 2;
test1[2] = 3;
}
Edit: You can only declare variables directly inside the class. A declaration statement can, however, also include initialization (on the same line):
int[] arrayA; // declare an array of integers
int[] arrayB = new int[5]; // declare and create an array of integers
int[] arrayC = {1, 2, 3}; // declare, create and initialize an array of integers
The following, on the other hand, is not a declaration and involves only initialization:
arrayB[0] = 1;
and so it can't go directly under the class. It must be enclosed within a method, constructor or initialization block.
See Also:
Arrays Java tutorial at Oracle
To work your java source file must be something like this:
public class Test
{
// this works
private static int[] test2 = {1,2,3};
// this is ok
private static int[] test1 = new int[3];
public static void main( String args[] ){
test1[0] = 1;
test1[1] = 2;
test1[2] = 3;
}
}
You can also put the code in a static initialization block which is executed when the class is loaded.
public class Test {
// this works
private static int[] test2 = {1,2,3};
// this is ok
private static int[] test1 = new int[3];
static {
test1[0] = 1;
test1[1] = 2;
test1[2] = 3;
}
}
精彩评论