我正试图编写一个程序,让您在两件事之间做出选择。但在执行了我选择的选项后,我希望能够返回相同选项的开头。
switch (option) {
case 1:
System.out.println("Start of option 1");
//option 1 will do things here
System.out.println("End of option 1");
//I want to return at the beginning of this case at the end of it
break;
case 2:
System.out.println("Start of option 2");
//option 2 will do things here
System.out.println("End of option 2");
//I want to return at the beginning of this case at the end of it
break;
default:
break;
}
还有一个退出所选案例的选项。此外,使用if语句来实现我想要做的事情会更容易吗?
case 2:
case2sub();
default:
break;
}
}
public static void case2sub() {
System.out.println("Start of option 2");
//option 2 will do things here
System.out.println("End of option 2");
//I want to return at the beginning of this case at the end of it
boolean end = false;
System.out.println("QUIT? (Y/N)");
keyboardInput = new Scanner(System.in).nextLine();
if (keyboardInput.equalsIgnoreCase("Y"))
end = true;
else{}
if (end){}
else
case2sub();
}
如果你把你的案例放在它们自己的方法中,你可以递归地调用它们,直到你放入一个exit语句。递归有效,while循环也有效。
public static void case2sub() {
boolean end = false;
while (!end)
{
end = false;
System.out.println("Start of option 2");
//option 2 will do things here
System.out.println("End of option 2");
//I want to return at the beginning of this case at the end of it
System.out.println("QUIT? (Y/N)");
keyboardInput = new Scanner(System.in).nextLine();
if (keyboardInput.equalsIgnoreCase("Y"))
end = true;
}
}
您可以通过多种方式退出。这只是两个答案。