gpt4 book ai didi

java - 如何将骰子游戏程序循环 3 次?

转载 作者:行者123 更新时间:2023-12-01 23:27:07 26 4
gpt4 key购买 nike

我正在尝试创建一个连续掷 2 组骰子 3 次的游戏。它让用户猜测一次 2-12 之间的数字。如果这个猜测与三轮中的任何一个匹配,他/她就赢了,否则他/她就输了。我有另一个类来显示结果,并且有一个计数器来显示它已经经过了多少次循环。如果用户正确猜对了它,结果为 0,否则结果为 1。我猜循环只循环一次,所以如果有人能指出我做错了什么,让它循环三次(并停止如果用户回答正确)。

import javax.swing.JOptionPane;


/**
* @author Marcus
*
*/
public class Dice {


int randomDieNum1;//random number generator for dice
int randomDieNum2;//random number generator for dice
private final int MINVALUE1 = 1, //minimum die value
MAXVALUE1 = 6;//maximum die value
private final int MINVALUE2 = 1, //minimum die value
MAXVALUE2 = 6;//maximum die value
int userNum = Integer.parseInt(JOptionPane.showInputDialog(null, "Guess a number between 1-12", "Guess a Number",
JOptionPane.INFORMATION_MESSAGE));//gets user input
String result ; //results
int start = 0 ; //counter to see how many turns were taken
public Dice()
{
for (int i = 1 ; i <= 3; i++)
randomDieNum1 = ((int)(Math.random()* 100) % MAXVALUE1 + MINVALUE1);
randomDieNum2 = ((int)(Math.random()* 100) % MAXVALUE2 + MINVALUE2);
int total = randomDieNum1 + randomDieNum2;
if (randomDieNum1 + randomDieNum2 != userNum)
{
result = "You did not guess the \n number correctly";
++ start;
}
else if (randomDieNum1 + randomDieNum2 == userNum)
{
result = randomDieNum1 + "+" + randomDieNum2 + "=" + total + "\n" +
"You guessed the number correctly";
}
else
{
result = "You Did not guess the number correctly";
}

}
public String get() //used in another class to display count
{
String temp;
temp = "" + start;
return temp;
}

}

编辑 多谢你们。我添加了这两个建议,并在用户得到正确答案后添加了一个中断来停止循环。它看起来像这样:

public Dice()
{
for (int i = 1 ; i <= 3; i++)
{randomDieNum1 = ((int)(Math.random()* 100) % MAXVALUE1 + MINVALUE1);
randomDieNum2 = ((int)(Math.random()* 100) % MAXVALUE2 + MINVALUE2);
int total = randomDieNum1 + randomDieNum2;
if (randomDieNum1 + randomDieNum2 == userNum)
{result = randomDieNum1 + "+" + randomDieNum2 + "=" + total + "\n" +
"You guessed the number correctly";
++ turns; //
break; //stops the loop if condition is meet
}

else if(randomDieNum1 + randomDieNum2 != userNum)
{
result = "You did not guess the \n number correctly\n\n";
++ turns;
}
}
}

最佳答案

除了缺失的{for (int i = 1 ; i <= 3; i++) {

您可能需要重新考虑 if 中使用的逻辑情况

if(x+y != c)
{// do operation A}
else if (x+y == c)
{// do operation B}

else else-if之后的条件永远不会被处决。

关于java - 如何将骰子游戏程序循环 3 次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19828161/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com