Java 从一个单独的方法结束游戏

Java 从一个单独的方法结束游戏,java,Java,我有两个不同的类:TextBasedGame和IntroductionChoices。 IntroductionChoices做出所有决定,而TextBasedGame基本上只是打印故事(它是带有main方法的) 我想知道的是,如果用户做出错误的选择,如何结束游戏。 在这种情况下,如果用户键入“删除组”,则会显示一条消息,游戏结束。在我的例子中,在主要方法中,它只是继续进行。如何阻止游戏运行 我在想,我可以以某种方式,在主要方法中,检查从介绍中返回的选项是否为“游戏结束”,并在那里结束游戏

我有两个不同的类:TextBasedGame和IntroductionChoices。 IntroductionChoices做出所有决定,而TextBasedGame基本上只是打印故事(它是带有main方法的)

我想知道的是,如果用户做出错误的选择,如何结束游戏。 在这种情况下,如果用户键入“删除组”,则会显示一条消息,游戏结束。在我的例子中,在主要方法中,它只是继续进行。如何阻止游戏运行

我在想,我可以以某种方式,在主要方法中,检查从介绍中返回的选项是否为“游戏结束”,并在那里结束游戏

   //Snippet from the main method
   System.out.println("What do you do?");    

   System.out.println(choice.choice1());

   System.out.println("Next part...");

   //Method choice1 from IntroductionChoices
   public static String choice1()
   {
       Scanner scan = new Scanner(System.in);

       System.out.println("Warn her of her shadows.");
       System.out.println("Take down the group.");

       String decision = scan.next();

       if (decision.equalsIgnoreCase("right decision"))
       {
           System.out.println("some text");
        return "some more text in continuation to continue story in main";
       }

       else if (decision.equalsIgnoreCase("wrong decision"))
       {
           System.out.println("You creep towards the men, hoping to surprise them from behind.");

           System.out.println("Consequence");

           return "GAME OVER";
       }

       else
       {
           return "That is not a valid response.";
       }
}
你不需要返回任何东西,它会结束程序

为用户提供一个选项:

  • 开始新游戏->开始新游戏

  • 退出->
    系统。退出(0)

  • 我也会用一个开关来检查用户选项,你不太容易出错,而且当选项开始累积时,它会更整洁、更快

    您可以创建选项枚举,或者使用具有有意义名称的最终整数,以便代码更易于导航并与用户选项匹配


    我想您可能希望显示
    main
    方法的循环部分。您可以在main方法中检查返回的字符串(或其他一些值,如enum)。您只需在
    choice()
    方法中
    抛出
    异常
    ,然后在main中捕获它。您不能只测试返回的内容吗<代码>字符串选择=choice1();如果(选择相等(“游戏结束”))返回向我们展示如何调用choice1()。如果“结束游戏”应该允许启动另一个游戏,那么该怎么办?@Bohemian,难道你不能要求用户输入(他们想启动一个新游戏吗),如果否,则返回System.exit,否则重置变量并调用启动函数(无论如何都应该清除变量)?
    System.exit(0)
    
    
    else if (decision.equalsIgnoreCase("wrong decision"))
    {
        System.out.println("You creep towards the men, hoping to surprise them from behind.");
    
        System.out.println("Consequence");
    
        System.exit(0);