Arrays constants can only be used in initializers error
Consider:
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"},
How can I make it so I can call the array from a different method?
That means you have to initialize it like this:
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){
...
}
If you want to use the array initializer, you cannot split the declaration and assignment.
You have two options: In the declaration
private static String[][] item = {...};
OR
Elsewhere using the new
keyword
private static String[][] item = new String[][]{...}
Also, you'll need to change public proj
to public class
I'm not 100% sure if I got correctly what you mean, but you can reference static class members by fully qualifying it.
public class MyClass {
// static class member
public static String myStaticArray;
// non-static class method
public void myMethod() {
MyClass.myStaticArray = {...}; // do stuff
}
}
You can declare a multidimensional array globally like this:
String [][] 2DArray;
And then initialize the same in the main method as follows:
2DArray = new String[][] {
{"array_element_0", "array_element_1"},
{"array_element_2", "array_element_3"},
...
};
If your target is: 1. declare it somewhere; 2. initialize it somewhere else; 3. still want to use the {...} format. This will work:
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;
精彩评论