Java 创建循环是一个随机值,每次循环重新启动时都会更改
我正在做一个抛硬币模拟器,但我有一个随机值的问题。我需要创建一个随机值,每次while循环再次启动时都会更改Java 创建循环是一个随机值,每次循环重新启动时都会更改,java,loops,random,while-loop,Java,Loops,Random,While Loop,我正在做一个抛硬币模拟器,但我有一个随机值的问题。我需要创建一个随机值,每次while循环再次启动时都会更改 System.out.println("How many times do I flip the coin?"); int repetition; int heads = 0; int tails = 0; Scanner amount_of_times = new Scanner(System.in); repetition =
System.out.println("How many times do I flip the coin?");
int repetition;
int heads = 0;
int tails = 0;
Scanner amount_of_times = new Scanner(System.in);
repetition = amount_of_times.nextInt();
double luck = (Math.random());
do {
if (luck > 0.5)
heads++ ;
else
tails++ ;
repetition --;
} while (repetition > 0);
System.out.println("The amount of heads was " + heads + ", meanwhile the amount of tails was " + tails + ".");
amount_of_times.close();
}
}
在循环之前,
luck
只分配一次值。如果希望它在每次迭代中获得不同的值,则应将赋值移动到循环内的:
do {
double luck = Math.random(); // Here!
if (luck > 0.5)
heads++ ;
else
tails++ ;
repetition --;
} while (repetition > 0);
Movedouble luck=(Math.random())代码>在循环中请参见:。