如何使用if语句来了解播放器或计算机是否赢了?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使用if语句来了解播放器或计算机是否赢了?相关的知识,希望对你有一定的参考价值。
我刚刚开始学习java,所以我可能甚至没有走上正确的轨道,但我有一个任务要求我创建一个21的游戏。游戏的工作方式是玩家和计算机轮流进入1,2,或3.输入达到或超过21的数字的玩家。我似乎遇到的麻烦是,当输入最终数字时,我似乎无法让程序退出循环,并且它将显示玩家每次输掉,输赢。
我尝试在do-while循环后使用另一个if语句来显示“You Win!”或者“你失去了。”但是,我无法弄清楚我应该在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!");
另一答案
在用户输入数字后,您应立即检查它们是否达到21(并且还输出该点的总数)。如果21没有被击中,那么计算机应该猜测,然后再次检查以查看21是否被击中。所以你将有两个if语句(每次猜测后一个;用户/计算机)。在用户猜测之后的else块中是计算机猜测的位置。您的if语句将检查> = 21,表示适当的用户或计算机丢失。你不需要在循环之外声明一个胜利者,因为这可以在循环中完成......
例如:
int total = 0;
do
System.out.print("\nEnter a 1, 2, or 3 >> ");
points = input.nextInt();
total = total + points;
System.out.println("The new total is " + total);
if (total >=21)
System.out.println("You lost! The computer is the victor.");
else
int random = (int )(Math.random() * 3 + 1);
total = total + random;
System.out.println("The computer entered a " + random);
System.out.println("The new total is " + total);
if(total >= 21)
System.out.println("You Win!");
while(total < 21);
以上是关于如何使用if语句来了解播放器或计算机是否赢了?的主要内容,如果未能解决你的问题,请参考以下文章
如何使if语句更小并避免在java中为相同的原因使用太多的循环