java - 如何使用 if 语句来知道玩家或计算机是否获胜?

标签 java loops if-statement

我刚刚开始学习java,所以我什至可能没有走在正确的轨道上,但我有一个作业要求我创建一个 21 的游戏。游戏的工作方式是玩家和计算机轮流输入 1、2 或 3。输入满足或超过 21 的数字的玩家就输了。我似乎遇到的麻烦是,当输入最终数字时,我似乎无法让程序退出循环,并且它会显示玩家每次都输了,无论赢还是输。

我尝试在 do-while 循环之后使用另一个 if 语句来显示“你赢了!”或“你输了”。但是,我不知道应该在 if 语句中使用哪些参数来决定谁赢了。我还尝试将游戏设置为玩家为偶数,计算机为奇数,但我无法将这些数字添加到运行总数中以结束循环。

  int numLoops = 0;
  int firstCheck;
  int points;
  Scanner input = new Scanner(System.in);

  do
  {
     System.out.print("\nEnter a 1, 2, or 3 >> ");
     points = input.nextInt();

     int random = (int )(Math.random() *  3 + 1);
     numLoops = points + numLoops + random;

     if(numLoops < 21)
     {
        System.out.println("The computer entered a " + random);         
        System.out.println("The new total is " + numLoops);
     }
     else
     {
        //This is what always prints.
        System.out.println("You lost! The computer is the victor.");
     }
  }while(numLoops < 21);
  //this is what I am having most of my trouble with.
  System.out.println("You Win!");

我预计循环将在总数达到 21 后关闭,并输出一个根据谁获胜而变化的语句。然而,程序总是输出玩家输了。

最佳答案

如果做了一些改变来简化事情。看一下源代码,它应该有详细的文档并且解释得最好。

/*
 * Which players turn is it?
 * (true for human player, false for computer)
 */ 
boolean isHumanPlayersTurn = true;
int totalPoints = 0;

Scanner input = new Scanner(System.in);

// the game ending condition
while (totalPoints < 21) {

    // take an action, depending on the players turn
    if (isHumanPlayersTurn) {
        System.out.print("\nEnter a 1, 2, or 3 >> ");
        totalPoints += input.nextInt();
    } else {
        int random = (int) (Math.random() * 3 + 1);
        System.out.println("The computer takes " + random);
        totalPoints += random;
    }

    System.out.println("Total amount is " + totalPoints);

    /*
     * Important part: After each players move, change the players turn, but do NOT
     * do this if the game already ended, since then the other player would have won.
     */
    if (totalPoints < 21) {
        isHumanPlayersTurn = !isHumanPlayersTurn;
    }
}

// now, the player to move is the one who loses
if (isHumanPlayersTurn) {
    System.out.println("You lost! The computer is the victor.");
} else {
    System.out.println("You Win!");
}

关于java - 如何使用 if 语句来知道玩家或计算机是否获胜?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55308324/

相关文章:

java - 命令行 Java + Jar 文件

java - GWT 捕获 HttpServlet 抛出的异常

java - 如何打印下面的图案

c++ - 如何检查数组的3个元素是否具有相同的值

php - setter/getter 中重复开关的设计模式?

java - 找到用死 Groovy 代码填充 PermGen 的代码

javascript - 将新属性推送到循环内的当前对象

javascript - 随机生成的数字 - "Check"函数

IF语句中的javascript变量范围

java - 使用 window.open() 打开 PDF 文件