Java返回循环问题

时间:2014-11-07 11:17:31

标签: java loops return jcreator

我正在为老虎机模拟器编写程序,我的大多数代码都在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 来结束游戏,则会将其定向到结束游戏菜单。
在我的if循环之外有一组单独的while语句来确定用户是否已离开循环,因为他没有信用或他已选择结束游戏。

//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,所以有人知道我该怎么做吗?我被困在一个循环之外,无法重新进入! (我已经想过在所有事情之外做另一个循环......)

3 个答案:

答案 0 :(得分: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;
    }
}

答案 1 :(得分:0)

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

的方法

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

我希望有帮助

答案 2 :(得分: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;


        }

    }
}