数组常量只能在初始化程序错误中使用



考虑:

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

如何使它可以从不同的方法调用数组?

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

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){
     ...
}

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

您有两个选项:在申报中

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

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

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

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

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

您可以全局声明一个多维数组,如下所示:

String [][] 2DArray;

然后初始化相同的主方法如下:

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

如果您的目标是: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;

相关内容

  • 没有找到相关文章

最新更新