我刚刚开始学习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之后关闭,并输出一条语句,该语句根据获胜者而有所不同。但是,程序总是输出玩家输了。
答案 0 :(得分:0)
如果进行了一些更改以简化操作。看看源代码,它应该有充分的文档记录,并能最好地说明事情。
/*
* 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!");
}
答案 1 :(得分:0)
在用户输入数字之后,您应立即检查是否达到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);