作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
一段时间以来,我一直试图找出这段代码中的错误所在,但我就是想不出来。该程序将 6 面骰子滚动 300 次,然后输出每个数字滚动的次数。但出于某种原因,它没有滚动 300 次,而是滚动了 320 次。我没有发现 for 循环有任何问题,所以我真的很茫然。
public static void dieRoll(){
int[] roll = new int [300];
int[] count = new int[] {1,2,3,4,5,6};
for(int i = 1; i<300; i++){
roll[i] = (int) Math.ceil( (int) (Math.random()*6)+1 );
// roll[i] = (int) Math.ceil(roll[i]);
// System.out.println(roll[i]);
if(roll[i]==1){
count[0]++;
}
else if(roll[i]==2){
count[1]++;
}
else if(roll[i]==3){
count[2]++;
}
else if(roll[i]==4){
count[3]++;
}
else if(roll[i]==5){
count[4]++;
}
else if(roll[i]==6){
count[5]++;
}
// System.out.println(roll[i]);
}//i loop
System.out.println("The die landed on 1 " + count[0] + " times.");
System.out.println("The die landed on 2 " + count[1] + " times.");
System.out.println("The die landed on 3 " + count[2] + " times.");
System.out.println("The die landed on 4 " + count[3] + " times.");
System.out.println("The die landed on 5 " + count[4] + " times.");
System.out.println("The die landed on 6 " + count[5] + " times.");
System.out.println("The die was rolled this many times: " + (count[0]+count[1]+count[2]+count[3]+count[4]+count[5]));
}//dieRoll()
如果有人可以指出错误可能出现的地方,那就太棒了。谢谢。
最佳答案
你像这样初始化你的计数:
int[] count = new int[] {1,2,3,4,5,6};
现在,1 + 2 + 3 + 4 + 5 + 6 等于 21。您的循环从 1 到 299,即 299 次迭代。当然,299 + 21 就是 320。
您应该将数组初始化为全零。
最后,您的代码可以简化:
for( int i = 0; i < 300; i++ )
{
roll[i] = (int) Math.ceil( (int) (Math.random()*6)+1 );
count[roll[i] - 1]++;
}
关于java - 在 Java 中创建一个单次掷骰子程序,但不是掷骰子 300 次,而是掷骰子 320 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31237305/
当用户在 uisearchbar 中键入文本时,我正在过滤一个数组,但问题是我有一个警报处理程序,每次调用委托(delegate)时都会触发该处理程序,但我希望警报出现只有一次没有多次......代码
我有一个 HTML5、jQuery 卡片内存游戏,您可以通过一次翻转两张卡片来匹配卡片。我想在两张卡片匹配时播放动画,但因为我已经将 "transform: rotationY(180deg)" 应用
在我的 Jboss-EAP-6.1 中,我部署了一个名为 'myRealWebApp.war' 的 .war我可以使用此网址访问我的应用程序 - http://mywebsite.com/myReal
我是一名优秀的程序员,十分优秀!