0

我正在为老虎机模拟器编写一个程序,我的大部分代码都在一个 while 循环中。

System.out.println("            *    Choose an option:       *       ");
System.out.println("            *   1: Display credit count. *       ");
System.out.println("            *   2: Play Again.           *       ");
System.out.println("            *   3: End Game.                     ");

如果用户选择3结束游戏,他将被引导到结束游戏菜单。在我的循环之外
有一组单独的语句来确定用户是否因为没有积分或选择结束游戏而离开了循环。ifwhile

//The case in which the user ended the game.
else {
    System.out.println("");
    System.out.println("You have ended the game. You have finished with a total of: "+credits+" credits!");
    System.out.println("");
    System.out.println("Next player?");
    System.out.println("");
    System.out.println("1: Yes, there is another player that would like to start with my "+credits+" credits.");
    System.out.println("2: Yes, there is another player, but he will start with 10 credits.");
    System.out.println("3: No, End the game.");
    selection2 = in.nextInt();
} 

我想要做的是:如果用户输入1,它将带他回到主游戏循环的开始。

我知道没有 goto cmd,所以有人知道我该怎么做吗?我被困在一个循环之外,无法重新进入!(我考虑过在一切之外再做一个循环......)

4

3 回答 3

0

不要一开始就退出循环...

enum Menu {START, MAIN, EXIT, ETC}
Menu menu = Menu.START;
boolean running = true;

while ( running )
{
    switch ( menu )
    {
        case START:
            // show and handle start menu here

            // As an extra note, you could/should create methods for each menu (start, main, ...)
            // Then call these methods from within the case statements
            break;
        case MAIN:
            // show and handle main menu here

            menu = Menu.EXIT; // This is an example of how to "change" menus
            break;
        case EXIT:
            // show and handle exit menu here
            running = false; // will cause the execution to leave the loop
            break;
        case ETC:
            // ... etc ...
            break;
    }
}
于 2014-11-07T11:26:33.203 回答
0

您可以做的是创建一个名为goToLoop()

在该方法内部放置循环的所有代码,因此当您想返回循环时,只需调用goToLoop()

我希望这会有所帮助

于 2014-11-07T11:28:29.867 回答
0

这是一些不完整的代码,可以让您了解状态模式。

interface IState {


   void action();
}



class InitialState implements {

   void action()
    {
        System.out.println("");
        System.out.println("You have ended the game. You have finished with a total of: "+credits+" credits!");
        System.out.println("");
        System.out.println("Next player?");
        System.out.println("");
        System.out.println("1: Yes, there is another player that would like to start with my "+credits+" credits.");
        System.out.println("2: Yes, there is another player, but he will start with 10 credits.");
        System.out.println("3: No, End the game.");
        selection2=in.nextInt();

        switch (selection2) 
        {
            case 2:
               currentState = new OtherGameState();
               break;


        }

    }
}
于 2014-11-07T11:30:16.173 回答