Java 需要帮助重新运行我的主类而不终止程序吗
所以基本上,我试图在一个类中只使用IF语句来制作一个小游戏,到目前为止,一切都很顺利。我最大的问题是“返回”提示。我尝试了system.exit(0),但因为它会杀死程序,所以这不是答案。我的问题是,你如何“重新管理”这个班级?例如,当您在“选项”菜单中时,如何返回主菜单Java 需要帮助重新运行我的主类而不终止程序吗,java,Java,所以基本上,我试图在一个类中只使用IF语句来制作一个小游戏,到目前为止,一切都很顺利。我最大的问题是“返回”提示。我尝试了system.exit(0),但因为它会杀死程序,所以这不是答案。我的问题是,你如何“重新管理”这个班级?例如,当您在“选项”菜单中时,如何返回主菜单 import java.util.Scanner; public class Main { public static void main (String[]args) { //Main Me
import java.util.Scanner;
public class Main {
public static void main (String[]args)
{
//Main Menu Prompt.
System.out.println ("Welcome to my mini parkour game!");
System.out.println ("Decide which trick to use, and don't mess up!");
System.out.println ("Choose one: Play, Quit");
Scanner bruh = new Scanner (System.in);
String MainMenu = bruh.nextLine ();
// Quit Prompt.
if (MainMenu.equals ("Quit"))
{
System.out.println ("You have quit the game.");
System.exit (0);
}
// Play Prompt.
if (MainMenu.equals ("Play"))
{
System.out.println ("Proceed to level 1, 2, 3, 4, 5, 6, 7, 8, 9, 10");
Scanner playgame = new Scanner (System.in);
String LevelSelect = playgame.nextLine ();
if (LevelSelect.equals ("1"))
{ System.out.println("You have reached this block of code!");
}
}
//code block to remind that java is case sensitive.
else {
System.out.println("error, try picking one again. (case sensitive.)");
return new Main();
}
}
}
我希望输出在主菜单提示符处,即使您在播放提示符处,也不会终止程序。我相信由存储在变量中的用户输入控制的while循环会起到神奇的作用。您必须学习如何使用while循环 如果您想升级到上帝级Java程序员,请使用enum定义您的状态,然后使用switch case在内部创建while循环状态机。 我太懒了,无法从我的手机中键入工作代码,但在高级上是这样的:
enum State { PLAY, QUIT };
public static void main(String[] args) {
boolean runAgain=true;
State state;
while (runAgain) {
//get the input from user
//update state
switch(state) {
case PLAY :
// update state
break;
case QUIT:
// update STATE
break;
//case WHATEVERELSE...
default:
assert false : "never get here";
}
}
}
这是一个学习和阅读java规范的过程,但是,嘿,在这样做之后,你将能够为……编写一个工作算法。。。。电梯!
祝你好运 为什么不把你的逻辑放在一段时间内呢?无论你在读什么书或教程,都会很快教会你关于循环的知识。等待它或直接跳到该部分。而不是
returnnewmain()代码>,您可以运行main(args)代码>您希望返回新的Main()的具体内容;怎么办?您所做的似乎是创建新对象,而不适当地清理现有对象ones@dan1st不,您不使用递归作为循环的替代实现。将循环用作循环。递归适用于有推送和弹出状态,以及有明确定义的边界条件的情况。这种情况无法通过两项测试。