为我正在制作的项目创建了这个程序,但我似乎无法弄清楚为什么它从未在结果中给出任何1.我在这里踢自己因为它可能很简单.
为了清楚起见:程序必须滚动两个单独的模具36k次并显示结果.
import java.util.Random; //Going to need this
public class Dicerolling { //Start Class
public static void main( String[] args)
{ //Start of Main
Random randomNumbers = new Random(); // Generates random numbers
int[] array = new int[ 13 ]; // Declares the array
int dice1 = 0;
int dice2;
int total;
//Roll the die 36,000 times
for ( int roll = 1; roll <=36000; roll++ )
dice1 = 1 + randomNumbers.nextInt ( 6 );
dice2 = 1 + randomNumbers.nextInt ( 6 );
total = dice1+dice2;
++array[total];
System.out.printf( "%s%10s\n", "Face", "Frequency" );
// outputs array values
for ( int face = 1; face < array.length; face++ )
System.out.printf( "%4d%10d\n", face, array[ face ] );
//There we go
} // end main
}//End of Class
Run Code Online (Sandbox Code Playgroud)
评论已回答了您的问题.在数学上不可能两个骰子(常规编号,六边)的总和为1.
但是你的程序中也有一个严重的错误:
for ( int roll = 1; roll <=36000; roll++ )
dice1 = 1 + randomNumbers.nextInt ( 6 );
dice2 = 1 + randomNumbers.nextInt ( 6 );
total = dice1+dice2;
++array[total];
Run Code Online (Sandbox Code Playgroud)
...缩进错误,错误的缩进隐藏了一个错误.问题是"for"循环以第一个分号结束,最后3个语句不是循环的一部分.
你需要使用大括号:
for ( int roll = 1; roll <=36000; roll++ ) {
dice1 = 1 + randomNumbers.nextInt ( 6 );
dice2 = 1 + randomNumbers.nextInt ( 6 );
total = dice1+dice2;
++array[total];
}
Run Code Online (Sandbox Code Playgroud)
一些一般性建议:
始终使用大括号if和循环语句1.这样,你就不太可能用错误的缩进代码来欺骗自己.
使用自动缩进代码的IDE.
1 - 有些人不喜欢这样做,但我的经验是,在这种情况下额外的"句法噪音"是一件好事.当你在压力下工作时,这样的愚蠢错误很难追查.
| 归档时间: |
|
| 查看次数: |
465 次 |
| 最近记录: |