java - Java,根据用户输入返回程序中的上一步
问题描述
我有一个程序,其中向用户询问多项选择问题,每个问题的选择之一是退出。
如果选择退出,我必须询问用户是否要重新开始,如果是,我想循环回到某个检查点。如果不是,则程序终止。
下面是一个只有一个问题的简化示例。我正在尝试构建的程序有多个。
有没有一种方法不涉及嵌套循环上的嵌套循环?
import java.util.Scanner;
class RandomStuff {
/* this is not the actual program, just a simplified version to show what I'm trying to figure out
let's pretend perfect input
*/
public static void main (String[]args){
Scanner keyboard = new Scanner(System.in);
// checkpoint I wish to loop back to. Not the beginning of the program
System.out.println("Press 1 to continue, press 2 to cancel ");
int number = keyboard.nextInt();
String again;
switch(number){
case 1:
System.out.println("user chose to continue");
break;
case 2:
System.out.println("user chose to cancel");
System.out.println("start again? (yes/no)");
again = keyboard.next();
if("yes".equals(again)){
/* loop to checkpoint*/ }
else
System.exit(0);
break;
}
/* afterwards, a few other rounds of asking an input an looping to the same checkpoint
when appropriate. Essentially I'm looking for a method to loop back to checkpoint
from any decision to be made
*/
keyboard.close();
}
}
解决方案
使用递归函数是循环的最佳选择。您可以使用另一种方法,而不是在 main 方法中编写您的选择:
import java.util.Scanner;
class Random{
public static void Choice(Scanner keyboard){
System.out.println("Press 1 to continue, press 2 to cancel ");
int number = keyboard.nextInt();
String again;
switch(number){
case 1:
System.out.println("user chose to continue");
break;
case 2:
System.out.println("user chose to cancel");
System.out.println("start again? (yes/no)");
again = keyboard.next();
if("yes".equals(again)){
Choice(keyboard);
//Function will be called again
}
else
System.exit(0);
break;
}
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
Choice(sc);
}
}
但这也可以通过使用单个 do-while 循环轻松完成
看到这个:
import java.util.Scanner;
class Random{
public static void main(String args[]){
Scanner keyboard = new Scanner(System.in);
boolean run = true;
do{
System.out.println("Press 1 to continue, press 2 to cancel ");
int number = keyboard.nextInt();
String again;
switch(number){
case 1:
System.out.println("user chose to continue");
break;
case 2:
System.out.println("user chose to cancel");
System.out.println("start again? (yes/no)");
again = keyboard.next();
if("yes".equals(again)){
continue;
}
else
run = false;
//terimanting the loop
break;
}
}
while(run);{
System.out.println("User chose to exit");
System.exit(0);
}
}
}
我测试了这两个程序,它们运行良好,如果您有任何问题或无法理解某些内容,请告诉我。
推荐阅读
- javascript - Javascript 使用自定义按钮打开 Kendo UI 网格编辑器
- go - 如何使用 OnError 函数获取代理错误
- javascript - 使用 JavaScript 使用 React.js 创建动画计数器
- python - 将包含日期和时间的列更改为分别包含日期和时间的两列
- java - 如何在 SOAPConnectionFactory 中使用 SSL 和用户名/密码
- neo4j - 返回唯一节点且没有关系的路径
- angular - 更改角度应用程序中的默认加载页面
- android - 如何使用 Task.whenAllComplete 了解多种数据类型的结果类型
- list - 如何快速检查matlab中脚本的文件目录是否正确?
- discord - 在 Discord 上自动发送消息