2010-08-13 60 views
1

的各个元素,我很新的节目,我必须在这里失去了一些东西。第一部分起作用。第二部分发生错误。这是为什么?JAVA - 问题初始化数组的

// 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; 
+0

这应该工作,你可能想发布完整的代码 – 2010-08-13 04:04:29

+0

你可以请你发布你的整个java文件?根据您当前的问题很难确定您粘贴的范围。 – Catchwa 2010-08-13 04:05:26

回答

4

从您发布的东西,线条

test1[0] = 1; 
test1[1] = 2; 
test1[2] = 3; 

需要一个方法或构造函数中。看起来你在班级以外有他们。假设MyClass是你班级的名字。添加一个构造函数,并把三句话里面:

MyClass { 
    test1[0] = 1; 
    test1[1] = 2; 
    test1[2] = 3; 
} 

编辑:只能直接在类中声明变量。声明语句可以,但是,还包括初始化(在同一行):

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 

下,在另一方面,是不是一个声明,而且只需要初始化:

arrayB[0] = 1; 

所以不能直接下课。它必须包含在方法,构造函数或初始化块中。

另请参见:

Arrays Java tutorial at Oracle

+0

好猜。我没有想到他可能会在定义之后立即进行初始化。 – 2010-08-13 04:13:44

+0

这就是我所做的 - 让他们在课堂上与构造函数中的水平相比。我想我只是想知道为什么初始化的第一种方式(INT [] VAR = {X,Y,Z})工作类级别和其他方式没有。令人难以置信。 – ConfusedWithJava 2010-08-13 04:21:18

+0

@ConfusedWithJava - 查看我上面的修改 – samitgaur 2010-08-13 04:38:26

2

若要Java源文件必须是这样的:

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

你也可以把代码中的静态初始化块是当类加载时执行。

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