Java 掷硬币程序中的wins错误
由于某些原因,我的程序没有正确打印正确的百分比。我不知道我是不是设置错了,但我不知所措。如果有人能给我指出正确的方向,那就太棒了。这是一个简单的程序,用户掷硬币猜测硬币的正面或反面,然后告诉他们是否赢了。我遇到的问题是,当用户想要继续玩游戏时,如何计算赢的次数Java 掷硬币程序中的wins错误,java,Java,由于某些原因,我的程序没有正确打印正确的百分比。我不知道我是不是设置错了,但我不知所措。如果有人能给我指出正确的方向,那就太棒了。这是一个简单的程序,用户掷硬币猜测硬币的正面或反面,然后告诉他们是否赢了。我遇到的问题是,当用户想要继续玩游戏时,如何计算赢的次数 public static void main(String[] args) throws InterruptedException { // This program asks the user to predict a
public static void main(String[] args) throws InterruptedException {
// This program asks the user to predict a toss of a coin.
Scanner in = new Scanner(System.in);
boolean done = false;
String continuePlay = "";
float count = 0;
float wins =0;
do{
System.out.printf("Do you predict heads or tails for the coin toss: ");
String prediction = in.next();
System.out.print("Tossing the coin");
TimeUnit.SECONDS.sleep(1);
System.out.print(".");
TimeUnit.SECONDS.sleep(1);
System.out.print(".");
TimeUnit.SECONDS.sleep(1);
System.out.print(".");
TimeUnit.SECONDS.sleep(1);
System.out.println(".");
TimeUnit.SECONDS.sleep(1);
Random rand = new Random();
int toss = Math.abs(rand.nextInt()) % 2;
if(toss == 0){
System.out.print("It came up heads.");
}else{
System.out.print("It came up tails.");
}
if(prediction.equals("h") && toss==0){
System.out.print(" You win.");
wins ++;
}else if(prediction.equals("h") && toss !=0){
System.out.print(" You loose.");
}else if(prediction.equals("t") && toss==1){
System.out.print(" You win.");
wins ++;
}else if(prediction.equals("t") && toss!=1){
System.out.print(" You loose.");
}
// Ask user if they want to continue to play
System.out.print("\nDo you want to play again? (\"c\" to continue \"q\" to quit): ");
continuePlay = in.next();
if (continuePlay.equals("c")){
done = false;
} else done = true;
count ++;
}while(done == false);
double percentWon = (wins / count) * 100;
System.out.printf("Thanks for playing. You guessed my number %.0f%% of the time.\n", percentWon);
in.close();
}
}
可能错误在你的赢增量中。。。我想每次你赢了,你都会把赢数重置为1。。。在这里
}
if(prediction.equals("h") && toss==0){
System.out.print(" You win.");
wins =1;
}else if(prediction.equals("h") && toss !=0){
System.out.print(" You loose.");
}else if(prediction.equals("t") && toss==1){
System.out.print(" You win.");
wins=1;
}else if(prediction.equals("t") && toss!=1){
System.out.print(" You loose.");
}
试着换成
}
if(prediction.equals("h") && toss==0){
System.out.print(" You win.");
wins ++;
}else if(prediction.equals("h") && toss !=0){
System.out.print(" You loose.");
}else if(prediction.equals("t") && toss==1){
System.out.print(" You win.");
wins++;
}else if(prediction.equals("t") && toss!=1){
System.out.print(" You loose.");
}
拿赢++;最后结束。不,不是这样。我尝试了两场比赛,其中一场赢了,另一场输了,结果显示我赢了0%。它应该是打印,你赢了50%的时间。将int变量也更改为float,因为在int中,0,5是0。。。我没有测试你的代码,只是我的假设不要忘记标记为答案并调试你的代码;D