对不起基本问题,但我是Java的新手。
每次在main中执行do-while循环时,我都会遇到生成随机数的问题。当我删除do-while语句时,if语句工作正常并且似乎每次都会生成一个随机结果,但是当它在循环中重复时,它似乎只是重复初始结果。
这是我的代码:
import java.util.Random;
public class CoinToss {
private enum Coin{Heads, Tails};
Random randomNum = new Random();
private int result = randomNum.nextInt(2);
private int heads = 0;
private int tails = 1;
Coin coinFlip;
public void flip(){
if(result == 0){
coinFlip = Coin.Heads;
System.out.println("You flipped Heads!");
}else{
coinFlip = Coin.Tails;
System.out.println("You flipped Tails!");
}
}
}
我的方法主要是我似乎遇到问题:
import java.util.Scanner;
public class TossGame {
public static void main(String[]args){
CoinToss test = new CoinToss();
int choice;
System.out.println("Welcome to the coin toss game!");
do{
System.out.print("Enter 1 to toss coin or enter 0 to quit: ");
Scanner input = new Scanner(System.in);
choice = input.nextInt();
if (choice == 1){
test.flip();
}
else if (choice > 1){
System.out.println("Invalid entry - please enter 1 or 0: ");
choice = input.nextInt();
}
}while (choice != 0);
}
}
提前感谢您的建议!
答案 0 :(得分:4)
您需要将结果放在flip()
方法中,因此每次调用都会随机化。
private int result;
private int heads = 0;
private int tails = 1;
Coin coinFlip;
public void flip(){
result = randomNum.nextInt(2)
if(result == 0){
coinFlip = Coin.Heads;
System.out.println("You flipped Heads!");
}else{
coinFlip = Coin.Tails;
System.out.println("You flipped Tails!");
}
}
}
答案 1 :(得分:2)
你只是"翻转"一次,当您初始化result
时:
private int result = randomNum.nextInt(2);
当您致电flip
时,请获取其他结果:
public void flip(){
result = randomNum.nextInt(2); // Add this line
if(result == 0){
答案 2 :(得分:1)
每次调用flip()时都需要随机化一个翻转,而不是在构造CoinToss时:
public class CoinToss {
private enum Coin{Heads, Tails};
Random randomNum = new Random();
private int result;
private int heads = 0;
private int tails = 1;
Coin coinFlip;
public void flip(){
result = randomNum.nextInt(2)
if(result == 0){
coinFlip = Coin.Heads;
System.out.println("You flipped Heads!");
}else{
coinFlip = Coin.Tails;
System.out.println("You flipped Tails!");
}
}