2014-06-30 23 views
1

我遇到了this tutorial,想知道爲什麼Java編譯器會爲最後一個示例拋出一個錯誤。有人可以解釋嗎?鋸齒形陣列:非法表達式開始

下面是摘錄:

-

的Java醜:句法不平順與特設邏輯

在這種不規則的,但方便的語法:int[] v = {3,4};,它幾件事情在一個鏡頭: {數組類型聲明,賦值,元素聲明數,插槽滿足}。但是,這種語法特質不能一般使用。例如,以下是語法錯誤:

int[] v = new int[2]; 
v = {3, 4}; 

下面是您可以嘗試的完整代碼。

public class H { 
    public static void main(String[] args) { 
     int[] v = new int[2]; 
     v = {3,4}; 
     System.out.print(v[0]); 
    } 
} 

編譯器錯誤是:「illegal start of expression」。

+0

可能重複[如何聲明Java中的數組?](http://stackoverflow.com/questions/1200621/how-to-declare-an-array-在-JAVA) –

回答

2

的 「{}」 括號不能使用數組大小已經作出之後。代碼將不會運行,因爲它會嘗試將大小分配給已具有大小的數組。要在「int [] v = new int [2];」之後定義數組中的元素,必須使用「v [0] = 3;」和「v [1] = 4;」

0

這只是簡單地違背語法的規則。您可以執行以下任一操作來獲得相同的結果。

  1. int[] v = {3, 4};
  2. v[0] = 3; v[1] = 4;
3

試試這招:

public class H { 
    public static void main(String[] args) { 
     int[] v = {9,6}; // new array with default values 
     System.out.print(v[0]); 
     v = new int[]{3,4}; //note: this will create a new array 
     System.out.print(v[0]); 
    } 
}