数组常量只能用于初始值设定项错误

时间:2011-06-14 18:49:07

标签: java arrays multidimensional-array

考虑:

public proj 3 {

    static string [][]Item;

    public static void main(String [] args){

        Item[][] = {
             {"BH," , "Backhoe,"            , "200.00"},
             {"ER," , "Electric Rake,"      ,  "10.00"},
             {"EL," , "Electric Lawnmower," ,  "15.00"},
             {"TR," , "Trencher"            ,  "35.00"},
             {"MU," , "Mulcher,"            ,  "20.00"},
             {"TS," , "Tree Sprayer,"       ,  "22.00"},
             {"CP," , "Cider Press,"        ,  "30.00"},
             {"PR," , "Pruner,"             ,  "12.00"},
             {"GE," , "Gas Edger,"          ,  "20.00"},
             {"RO," , "Roller,"             ,   "8.00"},

我怎样才能这样做,所以我可以用不同的方法调用数组?

6 个答案:

答案 0 :(得分:13)

这意味着你必须像这样初始化它:

public class Proj3{

    public static String [][] Item = {
              {"BH," , "Backhoe," , "200.00"},
              {"ER," , "Electric Rake," , "10.00"},
              {"EL," , "Electric Lawnmower," , "15.00"},
              {"TR," , "Trencher" , "35.00"},
              {"MU," , "Mulcher," , "20.00"},
              {"TS," , "Tree Sprayer," , "22.00"},
              {"CP," , "Cider Press," , "30.00"},
              {"PR," , "Pruner," , "12.00"},
              {"GE," , "Gas Edger," , "20.00"},
              {"RO," , "Roller," , "8.00"}
         };

public static void main(String [] args){
     ...
}

如果要使用数组初始值设定项,则无法拆分声明和赋值。

答案 1 :(得分:5)

您有两种选择: 在声明中

private static String[][] item = {...};

OR

其他地方使用new关键字 private static String[][] item = new String[][]{...}

此外,您需要将public proj更改为public class

答案 2 :(得分:0)

如果我没有正确理解你的意思,我不能100%确定,但你可以通过完全限定它来引用静态类成员。

public class MyClass {
  // static class member
  public static String myStaticArray;

  // non-static class method
  public void myMethod() {
    MyClass.myStaticArray = {...}; // do stuff
  }
}

答案 3 :(得分:0)

如果你的目标是:1。在某处宣布它; 2.在其他地方初始化它; 3.仍然想使用{...}格式。 这将有效:

public proj 3 {

    static string [][]Item;

    public static void main(String [] args) {

        string[][] _Item = {
             {"BH," , "Backhoe," , "200.00"},
             {"ER," , "Electric Rake," , "10.00"},
             {"EL," , "Electric Lawnmower," , "15.00"},
             {"TR," , "Trencher" , "35.00"},
             {"MU," , "Mulcher," , "20.00"},
             {"TS," , "Tree Sprayer," , "22.00"},
             {"CP," , "Cider Press," , "30.00"},
             {"PR," , "Pruner," , "12.00"},
             {"GE," , "Gas Edger," , "20.00"},
             {"RO," , "Roller," , "8.00"}
        };
        Item = _Item;

答案 4 :(得分:0)

您可以像这样全局声明多维数组:

String [][] 2DArray;

然后在main方法中初始化相同内容如下:

 2DArray = new String[][] {
                {"array_element_0", "array_element_1"},
                {"array_element_2", "array_element_3"},
                ...
            };

答案 5 :(得分:-1)

 private static string[][] item = { .. };

以上是正确的方法。代码中的[] []有点奇怪;)