2010-08-13 95 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; 
    } 
}