是否可以声明String [] []类型的全局数组?

时间:2013-12-23 14:12:30

标签: java arrays multidimensional-array

我想做的是:

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

5 个答案:

答案 0 :(得分:1)

要正常创建数组,您至少需要设置数组的第一个维度,但通常你会像

那样设置它

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

如果使用

等元素初始化数组,则可以跳过维

2)new Type[][]..[]{{..{elements},},..}}

但是,如果您使用元素 在声明它的同一位置初始化数组 ,那么您可以跳过new Type[][]...[]部分并使用{{ 1}}喜欢

3){{..{elements},},..}}


在你的情况下你有案例2)因为你没有在你声明它的位置初始化你的数组。而不是

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

你需要把它写成

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

答案 1 :(得分:0)

尝试这种初始化:

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

这将动态定义您的multidimensional Array

答案 2 :(得分: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"}};
}

答案 3 :(得分:0)

了解pString[][]类型的变量,因此按以下方式初始化

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

在上面的代码pString[][]类型被分配给初始化为相同类型的对象。

当您尝试分配值时,可以指定像这样的索引

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

答案 4 :(得分:0)

尝试以下

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[][]{....};分配给planza

之前,您必须先放置{{1}}