这是一些我更愿意自己弄清楚的工作,尽管我似乎确实无法整理我的代码。在这部分代码中,我需要提供一个用户可以选择的菜单,然后执行进一步的功能。
基本上我要问的是如何允许用户选择一个将在 Switch 语句中获得的选项,尽管有人有更好的主意?
这是我的代码:
int menuchoice = 1;
String options;
switch (menuchoice)
{
case 1: options = "Transfer";
break;
case 2: options = "Recent transactions";
break;
case 3: options = "Display account details and current balance";
break;
case 4: options = "Quit";
break;
}
System.out.println(options);
我意识到“menuchoice = 1”不允许用户在不更改代码的情况下选择他们想要的选项?我觉得这有点令人困惑……我该怎么做?
最佳答案
您正在为每种情况声明一个新的字符串选项
,并且原始选项尚未初始化。 System.out.println(options) 使用的是范围内的原始未初始化的
String options = "Transfer";
直接使用
options = "Transfer";
全部更改
switch (menuchoice)
{
case 1: options = "Transfer";
break;
case 2: options = "Recent transactions";
break;
case 3: options = "Display account details and current balance";
break;
case 4: options = "Quit";
break;
}
此外,为了从用户那里获取菜单选择,您应该使用扫描仪
Scanner scanner = new Scanner(System.in); // scans the console.
System.out.println("Enter a menu option: "); // prints to console
int menuOption = scanner.nextInt(); // gets next int from console
关于Java应用程序提供不同选项的菜单吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20484088/