2013-12-23 70 views
0

是我想要做的是這樣的:是否可以聲明String [] []類型的全局數組?

class test{ 
public static String[][] p; 

} 

但什麼是錯的。 當我嘗試通過寫某物它:

p[][]={...}; 

它說:「P不能被解析爲一個類型」。

編輯: 好吧,我看到有一些問題與理解我在說什麼,所以我在這裏發佈代碼。

public class Test{ 
    static String[][] plansza; 
    public static void main(String []arg){ 

       p[][]={ {" ","A", "B", "C", "D", "E", "F", "G", "H"}, 
        {"1.","0","1","0","1","0","1","0","1"}, 
        {"2.","1","0","1","0","1","0","1","0"}, 
        {"3.","0","1","0","1","0","1","0","1"}, 
        {"4.","0","0","0","0","0","0","0","0"}, 
        {"5.","0","0","0","0","0","0","0","0"}, 
        {"6.","2","0","2","0","2","0","2","0"}, 
        {"7.","0","2","0","2","0","2","0","2"}, 
        {"8.","2","0","2","0","2","0","2","0"} 
        }; 
     } 
+6

這不是你如何「寫的東西吧。」參考[基礎教程](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html)。 – Maroun

+2

也許試試'p = new String [] [] {{...},{...}};'' – Pshemo

回答

0

指數試着像follwoing

public class Test{ 
static String[][] plansza; 
public static void main(String []arg){ 

      plansza = new String[][] { {" ","A", "B", "C", "D", "E", "F", "G", "H"}, 
       {"1.","0","1","0","1","0","1","0","1"}, 
       {"2.","1","0","1","0","1","0","1","0"}, 
       {"3.","0","1","0","1","0","1","0","1"}, 
       {"4.","0","0","0","0","0","0","0","0"}, 
       {"5.","0","0","0","0","0","0","0","0"}, 
       {"6.","2","0","2","0","2","0","2","0"}, 
       {"7.","0","2","0","2","0","2","0","2"}, 
       {"8.","2","0","2","0","2","0","2","0"} 
       }; 
    } 
} 

你必須把new String[][]{....};之前爲它分配給plansza

0

嘗試這種類型的初始化:

public static String[][] s = new String[][]{ 
    {"A", "B", "C"}, 
    {"D", "E", "F"} 
}; 

這將定義dinamically您multidimensional Array

0

您只能使用數組常量的初始化。

因此:

// will compile 
public static String[][] p = {{"foo", "bar"}}; 

// will compile 
public static String[][] p; 
static { 
    p = new String[][]{{"foo", "bar"}}; 
} 

// won't compile 
public static String[][] p; 
static { 
    p = {{"foo", "bar"}}; 
} 
0

明白pString[][]類型的變量,從而初始化它以下述方式

p = new String[][]{...}; 

在上面的代碼p這是String[][]類型的被分配給一個初始化相同類型的對象。

當您嘗試分配值,你可以指定這樣

p[i][j] = "value"; 
1

要創建數組通常你需要至少設置數組的第一維,但通常你會這樣做:

1)new Type[dim1][dim2]..[dimN]

,如果你的元素初始化數組一樣

2,您可以跳過尺寸)new Type[][]..[]{{..{elements},},..}}

但如果你在你所在的同一個地方元素初始化您的數組宣佈它那麼你可以跳過new Type[][]...[]部分,只是使用{{..{elements},},..}}

3)Type[][]..[] myArray = {{..{elements},},..}}


在你的情況你有情況2),因爲你沒有初始化數組中的地方,你宣佈它。因此,而不是

p[][] = { 
    {" ","A","B","C","D","E","F","G","H"}, 
    ... 
    }; 

你需要把它寫成

p = new String[][]{ 
    {" ","A","B","C","D","E","F","G","H"}, 
    ... 
    }; 
相關問題