gpt4 book ai didi

Java - 具有 If 语句打印顺序错误的主方法

转载 作者:行者123 更新时间:2023-12-02 04:06:36 26 4
gpt4 key购买 nike

如果这是任何类型的重复,我会提前申请,但我找不到任何可以解决我的具体问题的内容。

这是我的程序:

import java.util.Random;

public class CarnivalGame{

public static void main(String[] args){

int count = 0;
int wins = 0;
for (int i = 0; i < 101; i++){
System.out.println("Roll " + count);
count = count + 1;
int die1=(dieRoll(6));
int die2=(dieRoll(20));
int die3=(dieRoll(8));
int die4=(dieRoll(4));
int die5=(dieRoll(12));
int sum = die1+die2+die3+die4+die5;
System.out.println("Total: " + sum + "\n");

if ((sum >= 35) || (sum < 20)){
System.out.println("Player wins!\n");
wins = wins + 1;
}
if (count == 100){
//PROBLEM AREA
System.out.printf("After 100 rolls, the player has won for a total of %d times!\n", wins);
}
}//end for loop
}//end main

public static int dieRoll(int sides){
int num = 0;
int roll = 0;
Random rng = new Random();
if(sides >=4){
for(int i = 0; i < 1; i++){
roll = rng.nextInt(sides)+1;
System.out.println("Roll is: " + roll);
num = num + roll;
}//end for loop
}//end if
return num;
}//end method
}//end class

当前打印的内容:

本例中滚动计数 = 100

For loop (x100):

---> "After 100 rolls, the player has won for a total of (wins) times!" Roll (count)

Roll is: dieRoll(x)
Roll is: dieRoll(x)
Roll is: dieRoll(x)
Roll is: dieRoll(x)
Roll is: dieRoll(x)
Total: sum

if ((sum >= 35) || (sum < 20))
"Player wins!"

我试图打印出来的内容:

完全相同的事情,但是

 if ((sum >= 35) || (sum < 20))
"Player wins!"
---> "After 100 rolls, the player has won for a total of (wins) times!

所以基本上我试图找出为什么我的问题区域与卷计数一起打印,它应该在总和和“玩家获胜!”之后打印。

我假设这是我的 if 语句格式错误,但我不知道如何修复它。感谢您抽出时间。

最佳答案

你的问题是你的循环有 101 次迭代,从 0 到 100。因此,在数字 99 后,您的 100 次骰子掷骰就结束了,然后您再掷一次。只需将循环从 0 更改为 99(i<100 而不是 101)。

编辑(主要是因为我还不能直接回答你):

当你(尝试)迭代 100 次时,我真的不明白为什么你需要变量 count 。只需让你的循环掷骰子一百次,添加胜利,然后打印你的语句。

关于Java - 具有 If 语句打印顺序错误的主方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34227538/

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