数组常量只能在初始值设定项错误中使用

2022-09-04 01:53:05

考虑:

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

如何使它,以便我可以从其他方法调用数组?


答案 1

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

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

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


答案 2

您有两种选择:在声明中

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

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

此外,您需要更改为public projpublic class