尝试创建一个程序,模拟掷出 500 个骰子,并以星星的形式显示一、二、直到六的数量

  • 本文关键字:星星 显示 一个 创建 程序 模拟 java
  • 更新时间 :
  • 英文 :

public class looptests {
public static void main(String[] args) {
Random randGen = new Random();
int seedValue = 0;
randGen.setSeed(seedValue);
int i;          // Loop counter iterates numRolls times
int numRolls;   // User defined number of rolls
int numOnes = 0;
int numTwos = 0;
int numThrees = 0;
int numFours = 0;
int numFives = 0;
int numSixes = 0;   // Tracks number of 6s found
int diceOne; // Dice 1 values
int diceTwo;
int totalRolls = 0;  // Sum of dice values
numRolls = 500;
// Roll dice numRoll times
if  (numRolls >= 500);
for (i = 0; i < numRolls; i++) {
diceOne = randGen.nextInt(6);
diceTwo = randGen.nextInt(6);
totalRolls = diceOne + diceTwo;
if (totalRolls == 1) {
numOnes = numOnes + 1;
}
if (totalRolls == 2) {
numTwos = numTwos + 1;
}
if (totalRolls == 3) {
numThrees = numThrees + 1;
}
if (totalRolls == 4) {
numFours = numFours + 1;
}
if (totalRolls == 5) {
numFives = numFives + 1;
}
if  (totalRolls == 6) {
numSixes = numSixes + 1;
}
}
int count = 0;
while (count < 6) {
// Print statistics on dice rolls
System.out.println("One (" + numOnes + ")");
count++;
}
}
}

这就是我达到的程度,我遇到了几个问题,第一,这不是随机的,我一遍又一遍地得到相同的数字,其次,我没有设法显示"*"来反映我得到一两次的次数。 例:

一 (65(:

******两 (80(:

******三 (86(:

******四 (107(:

******五 (91(:

******六 (71(:

******

您获得相同的数字,因为您将相同的种子设置为随机实例。例如,通过 Math.random(( 生成随机种子,或者根本不设置种子。

要打印星星,您只需使用循环并按一个打印星星:

System.out.print("One (" + numOnes + ")");
for (int i = 0; i < numOnes; i++) {
System.out.print("*");
}
System.out.println();

考虑使用java.security.SecureRandom而不是java.util.Random它在加密上更安全。

我更喜欢这种生成星星的方式:

public static void main(final String[] args) {
System.out.println(pad('*', 25));
}
private static String pad(final char padChar, final int count) {
final char[]          pad = new char[count];
Arrays.fill          (pad, padChar);
return String.valueOf(pad);
}

它更高效、更灵活。

最新更新