Reputation: 189
Is there a better way to represent this menu structure in Java? I think the problem is that I'm declaring an array that contains Strings and arrays - not possible right?
String[][][] menu = {
"1. Select Store",
{
"1. Manage Stock",
{
"1. Buy More",
"2. Steal It"
},
"2. Fire Employee",
"3. Exit"
},
"2. List Stores",
"3. Exit"
};
So I tried this:
String[][][] menu = {
{"1. Select Store"},
{
{"1. Manage Stock"},
{
{"1. Buy More"},
{"2. Steal It"}
},
{"2. Fire Employee"},
{"3. Exit"}
},
{"2. List Stores"},
{"3. Exit"}
};
Still no better.
Upvotes: 0
Views: 812
Reputation: 3492
You need to make everything is at least a three deep array with one string in it:
String[][][] menu = {
{ { "1. Select Store" } },
{ { "1. Manage Stock" },
{ "1. Buy More", "2. Steal It" },
{ "2. Fire Employee" },
{ "3. Exit" } },
{ { "2. List Stores"} },
{ { "3. Exit" } }
};
Possibly a bit more complex than you are wanting but if each menu item knows about its sub menus then it is easier to keep track of it all. This will print out your example with similar indents.
public Menu(){
List<Option> options = new ArrayList<Option>();
Option buyMore = new Option("Buy More");
Option stealIt = new Option("Steal It");
Option manageStock = new Option("Manage Stock", Arrays.asList(buyMore, stealIt));
Option fireEmployee = new Option("Fire Employee");
Option exit = new Option("Exit");
Option selectStore = new Option("Select Store", Arrays.asList(manageStock, fireEmployee, exit));
Option listStores = new Option("List Stores");
Option exitStore = new Option("Exit");
options.addAll(Arrays.asList(selectStore, listStores, exitStore));
for(int i = 0; i < options.size(); ++i){
options.get(i).print("", i + 1);
}
}
class Option{
String title;
List<Option> subOptions;
public Option(String title, List<Option> subOptions){
this.title = title;
this.subOptions = subOptions;
}
public Option(String title){
this.title = title;
this.subOptions = new ArrayList<Option>();
}
public void print(String indent, int number){
System.out.println(indent + number + ". " + title);
for(int i = 0; i < subOptions.size(); ++i){
subOptions.get(i).print(indent + " ", i+ 1);
}
}
}
Upvotes: 1
Reputation: 34675
Based on the example data you've provided, you are looking for a tree structure, not a 3-dimensional array.
In a 3-dimensional array of Strings, you have an array, which contains only arrays, which contain only arrays, which contains only Strings. You are interspersing arrays with Strings, which is not permitted.
Upvotes: 2