Java随机数生成器生成相同的数字,但是当我比较它们时,它并不相同



我对Java编程很陌生。例如,即使我掷出相同的数字,我仍然输掉了赌注。如果我像一个人一样掷骰子并且很好,我仍然赢得了赌注金额。我正在尝试解决这个问题几个小时。但想不通。拜托,有人,帮帮我。提前谢谢。 这是我的代码。

public class Dice {
private int dice;
public Random number;
//default constructor
public Dice() {
number = new Random();
}
//To generate random number between 1 to 6. random starts from 0. there is no 0 on dice. 
//By adding one, it will start at 1 and end at 6
}
//Method to check two dice
public boolean isequal(int dice1,int dice2) {
}
else
}
public class Playgame
{
//
}
public static void main(String[] args) {
//
}
}
{
return false;
}
}
userinput.close();
}
}

这里至少有一个问题(可能还有其他问题(:

if(obj1.isequal(obj1.play(), obj1.play()) == true)
{
System.out.println("You rolled a " + toString(obj1.play()) + " and a "
+ toString(obj1.play()) );

打印消息时,您将再次调用obj1.play()并生成 2 个新的随机数。如果需要使用该值两次(一次用于比较,一次用于打印(,则应将其存储在变量中。

int firstRoll = obj1.play();
int secondRoll = obj1.play();
if(obj1.isequal(firstRoll, secondRoll) == true)
{
System.out.println("You rolled a " + toString(firstRoll) + " and a "
+ toString(secondRoll) );
//...

每次调用obj1.play()返回不同的值。

因此,您的测试:obj1.isEqual(obj1.play(), obj1.play())大多不会返回 true。

如果要生成随机数并检查两个数字是否相等,则不需要骰子类。 尝试下面的代码它将起作用

Random random = new Random();
int n1 = random.nextInt(6) + 1;
int n2 = random.nextInt(6) + 1;
System.out.println("You rolled a " + toString(n1)+ " and a " +toString(n2));
if (n1 == n2) {
double win = betmoney * 2;
System.out.println("You win $" + win);
startmoney += win;
} else {
startmoney -= betmoney;
System.out.println("You lose $" + betmoney);
System.out.println("You left only $" + startmoney);
}

您的代码问题在于您生成随机数两次 1.在条件检查期间和 2. 在 sysout 语句中。 您的程序仅工作正常。 但是由于这个原因,你让自己感到困惑。

每次调用 ob1.play(( 方法时,它都会给你不同的数字。

在 if 子句中:

if(obj1.isequal(obj1.play(), obj1.play()) == true)

将为您提供两个随机值,这些值不同于 if 块中的两个随机值:

System.out.println("You rolled a " + toString(obj1.play()) + " and a " + toString(obj1.play()) );

最新更新