我即将创建一个运行java控制台而不是GUI的应用程序,我对使用另一级子菜单显示菜单的最佳方法提出了疑问。我已经快速输入以下代码,以便让您了解我正在尝试实现的目标。
我的目标是修改帐户和访问帐户的菜单打开子菜单以进一步选择。从本质上讲,我试图通过选择太多来解决应用程序(例如更改帐户ID,更改帐户余额,更改帐户昵称等)。
我看到互联网上的一些地方似乎不喜欢这种类似“树状”的结构。是否有任何干净的方式做这样的事情,或者我会被迫做一些事情,比如创建单独的方法(即AccountMenu),它会显示不同的提示,并基本上创建另一个do while循环。
public class Console
{
public static void main (String[] args) {
System.out.println("Welcome to the console application");
int selection =0;
do
{
System.out.println("[1] Create New Account");
System.out.println("[2] Modify Account");
System.out.println("[3] Access Account");
System.out.println("[4] Quit");
System.out.print("Insert selection: ");
selection = ReadConsole.nextInt();
switch (selection)
{
case 1: dothislater; break;
case 2: dothislater; break;
case 3: dothislater; break;
case 4: System.out.println("Application has been shut down")
break;
default:
System.out.println("The selection was invaild!");
}
}while (selection != 4);
}
}
我是java的新手,而我只是这样做是为了愚弄它的样子。建议/想法?我还要提一下,我不想实现像swing元素这样的“适当”的GUI。
答案 0 :(得分:3)
您可以为每个(子)菜单制作另一个功能。 这不是因为它不符合OOP的精神。
public class Console {
private int testint = 1;
/**
* @param args
*/
public static void main(String[] args) {
Console console = new Console();
console = console.mainMenu(console);
System.out.println("Application has been shut down");
}
private Console mainMenu(Console console) {
System.out.println("Welcome to the console application");
int selection = 0;
do {
System.out.println("[1] Create New Account");
System.out.println("[2] Modify Account");
System.out.println("[3] Access Account");
System.out.println("[4] Quit");
System.out.print("Insert selection: ");
// selection = testint++;
selection = ReadConsole.nextInt();
switch (selection) {
case 1: return console.submenu1(console);
case 2: return console.submenu1(console);
case 3: return console.submenu1(console);
case 4: return console;
default:
System.out.println("The selection was invalid!");
}
} while (selection != 4);
return console;
}
private Console submenu1(Console console) {
System.out.println("Welcome to the SUBMENU");
int selection = 0;
do {
System.out.println("[1] SUBMENU_1");
System.out.println("[2] SUBMENU_2");
System.out.println("[3] SUBMENU_3");
System.out.println("[4] Return");
System.out.print("Insert selection: ");
//selection = ++testint;
selection = ReadConsole.nextInt();
switch (selection) {
case 1: return console.submenu1(console);
case 2: return console.submenu1(console);
case 3: return console.submenu1(console);
case 4: return console.mainMenu(console);
default:
System.out.println("The selection was invalid!");
}
} while (selection != 4);
return console;
}
}
可能需要更多调整,但你可能会得到这个想法