java - 我怎样才能在同一个方法中调用一个方法?

标签 java

我编写了一个 21 点程序,我希望每次玩家输掉时都执行方法 play()。如:

public void play()
   {
      System.out.println("Your balance: $" + playerBalance + "\nHow much would you like to bet?");
      playerBet = keyboard.nextInt();
      System.out.println("Your bet: $" + playerBet);



      if(playerTotalValue > 21)
      {
         playerBalance -= playerBet;
         System.out.println("You are busted.\nYour balance: $" + playerBalance);
         System.out.println("Press enter to continue...");
         keyboard.next();
         play();
      }   

      else if(dealerTotalValue > 21)
      {
         playerBalance += playerBet;
         System.out.println("The house is busted.\nYour balance: $" + playerBalance);             
         System.out.println("Press enter to continue...");
         keyboard.next();
         play();
      }

这当然不能像我想要的那样工作!任何帮助将不胜感激。

最佳答案

从自身调用一个方法被称为recursion .

你不想为此做递归,而是一个不断重复其主体直到玩家想要退出的循环或循环。

像这样:

public void play() {
    boolean playAgain = true;

    while (playAgain) {
        // Your game logic here.

        // When the game ends, ask the user if he/she wants to play again
        // and store the answer in the playAgain variable.
    }
}

关于java - 我怎样才能在同一个方法中调用一个方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28177906/

相关文章:

java - 如果只有线程,为什么我们需要对象监视器

java - 在ant中删除一个文件

java - Play 框架 [2.5.0 java] - 阻塞的 netty-event-loop 线程导致超时

java - android中将异步方法转为同步方法

java - 如何在java中对特定的二维数组进行排序

java - Vertx 尝试启动嵌入式服务器

java - 两个同步语句。它们是如何工作的?

java - Jersey 和 Google App Engine (GAE) 不适合我

java - Android java.lang.ClassNotFoundException (webrtc)

java - 条件查询 : order by count