第一个问题: 有一个while循环,在do部分有一个开关。在选择案例1之后,完成了一些计算,可以产生两个选项,如If语句中所示。我的问题是代码运行直到休息;然后直接回到菜单循环。我的问题:如何让程序为用户打印输出,然后继续菜单循环?
第二个问题: 在案例1中,有两个结果选项,第一个是失败的响应。从这里开始,如何让程序循环回到案例1的开头,再次询问用户输入?即使回到主菜单也没关系。
public static void showMenu() {
System.out.print('\u000c');
System.out.println("1 - Compute Change \n");
System.out.println("2 - Estimate Feast \n");
System.out.println("3 - \n");
System.out.println("4 - \n");
System.out.println("5 - I'm broke, get me out of here\n");
System.out.println("Select Option:\n");
}
public StackPost() {
System.out.println("Welcome to the Bank of Winterfell");
Scanner in = new Scanner(System.in);
do {
showMenu();
selection = in.nextInt();
switch (selection) {
case 1:
// get input, compute then decision:
if (something<somethingElse) {
// false response -
} else {
// correct response - system prints out some stuff back to user, back to main
// menu loop
}
break;
case 2:
break;
case 5:
System.out.println("\nEnding Now\n");
System.exit(0);
break;
default:
System.out.println("Instruction is invalid");
}
} while (selection != 5);
}
答案 0 :(得分:0)
您可以打印“按Enter键继续”(或在锁定程序之前要注意的任何内容),并在break
之前添加对Scanner#nextLine()的调用。这将锁定进度,直到用户按下进入。
case 2:
// Some code here...
// Done, now show result and tell user to press any key to continue
System.out.println("Some fancy result from case handle code");
System.out.println("Press enter to continue...");
in.nextLine();
break;
你可以添加一个不会让代码继续的while循环,直到第一种情况下预期的任何输入都可以接受。
case 1:
System.out.println("Some handle that tells user to input something, and what is acceptable");
String input = null;
while(!(input = in.nextLine()).equals("something")) {
System.out.println("Wrong input, try again...");
}
// Input is acceptable, now do something with it...
System.out.println(input);
System.out.println("Press enter to continue...");
in.nextLine();
break;
请注意,在您的代码中,您拨打Scanner#nextInt()
,并且#nextInt
不会因按Enter键而消耗\n
,因此会转移到切换案例中{的用法{1}}。您可以使用#nextLine()
来避免这种情况。
答案 1 :(得分:0)
您可以通过以下方式实现它:
return
语句。while
中使用case 1
循环在实施建议的解决方案后,StackPost()
方法将如下所示。您可以看到complete working code here:
public static void StackPost()
{
System.out.println("Welcome to the Bank of Winterfell");
try(Scanner in = new Scanner(System.in))
{
int selection;
do
{
showMenu();
selection = in.nextInt();
switch (selection)
{
case 1:
// get input, compute then decision:
while(true)
{
int something = in.nextInt();
int somethingElse = in.nextInt();
if (!(something<somethingElse)) {
// correct response - system prints out some stuff back to user, back to main
System.out.println("Print here the result");
// menu loop
return;
}
// false response - continue for next iteration in while-loop
}
//No need of 'break;' here
case 2:
break;
case 5:
System.out.println("\nEnding Now\n");
System.exit(0);
default:
System.out.println("Instruction is invalid");
}
} while (selection != 5);
}
}
注意:最佳做法是在处理实现try-with-resources
界面的系统资源时使用AutoCloseable
。