2D布尔数组创建和赋值。编译时错误

时间:2012-04-04 09:57:27

标签: java arrays initialization boolean multidimensional-array

public class Test {
    boolean[][] expectedResults = new boolean[8][2];
    expectedResults[0] = new boolean[] {false, false}; //00B
}       

给我以下编译时错误:

test.java:3:']'预计为         expectedResults [0] = new boolean [] {false,false}; // 00B
                        ^
test.java:3:';'预计
        expectedResults [0] = new boolean [] {false,false}; // 00B
                         ^
test.java:3:非法启动类型         expectedResults [0] = new boolean [] {false,false}; // 00B
                           ^ test.java:3:期待         expectedResults [0] = new boolean [] {false,false}; // 00B
                            ^ test.java:3:';'预期         expectedResults [0] = new boolean [] {false,false}; // 00B
                                ^ test.java:3:非法启动类型         expectedResults [0] = new boolean [] {false,false}; // 00B
                                        ^ test.java:3:期待         expectedResults [0] = new boolean [] {false,false}; // 00B
                                         ^ test.java:3:';'预期         expectedResults [0] = new boolean [] {false,false}; // 00B
                                          ^ test.java:3:非法启动类型         expectedResults [0] = new boolean [] {false,false}; // 00B
                                            ^ test.java:3:期待         expectedResults [0] = new boolean [] {false,false}; // 00B
                                                 ^ test.java:3:';'预期         expectedResults [0] = new boolean [] {false,false}; // 00B
                                                  ^ test.java:4:类,接口或枚举预期
}

解决

必须在方法中!

4 个答案:

答案 0 :(得分:5)

语法为:

expectedResults[0] = new boolean[]{false, false};

另外,请确保在方法或静态初始化块中执行赋值。

答案 1 :(得分:0)

您可以创建一个类似于此{false, false}的数组,只有当您将其与变量(Array constants can only be used in initializers)放在同一行时才会生成:

boolean[] expectedResults = {false, false}; // complies

虽然这不能编译:

boolean[] expectedResults;
expectedResults = {false, false}; // does not complie

改为使用:

boolean[] expectedResults;
expectedResults = new boolean[]{false, false};

答案 2 :(得分:0)

  

这是8x2布尔数组初始化变得容易。

  public boolean[][] expectedResults = {
    {false, false},
    {false, false},
    {false, false},
    {false, false},
    {false, false},
    {false, false},
    {false, false},
    {false, false},
  };
  

这是一个简单的4x8布尔数组初始化。

  public boolean[][] expectedResults = {
    {false, false, false, false, false, false, false, true},
    {true, false, false, false, false, false, false, true},
    {true, false, false, false, false, true, true, true},
    {false, true, true, true, true, true, true, false}
  };

答案 3 :(得分:-2)

我认为你必须像这样初始化数组。

boolean[][] expectedResults;
 expectedResults = new boolean[8][2];