【发布时间】:2018-02-05 03:07:28
【问题描述】:
我正在尝试创建一个数组来生成随机数并保存每个数字滚动的次数。然后我试图创建结果的直方图,但控制台变为空白。我想不出巧妙地使用循环的方法,所以我不得不使用非常粗略的解决方案。
import java.util.Random;
import java.util.Arrays;
public class DiceRolls {
public static void main(String[] args){
int[] diceRolls = new int [9];
Random rand = new Random();
for(int numberOfRolls = 0; numberOfRolls <= 20; numberOfRolls++){
int individualRolls = rand.nextInt(9);
diceRolls[individualRolls] ++;
}
for(int y = 0; y >= diceRolls[0]; y++){
System.out.print("*");
}
System.out.println(" ");
for(int y = 0; y >= diceRolls[1]; y++){
System.out.print("*");
}
System.out.println(" ");
for(int y = 0; y >= diceRolls[2]; y++){
System.out.print("*");
}
System.out.println(" ");
for(int y = 0; y >= diceRolls[3]; y++){
System.out.print("*");
}
System.out.println(" ");
for(int y = 0; y >= diceRolls[4]; y++){
System.out.print("*");
}
System.out.println(" ");
for(int y = 0; y >= diceRolls[5]; y++){
System.out.print("*");
}
System.out.println(" ");
for(int y = 0; y >= diceRolls[6]; y++){
System.out.print("*");
}
System.out.println(" ");
for(int y = 0; y >= diceRolls[7]; y++){
System.out.print("*");
}
System.out.println(" ");
for(int y = 0; y >= diceRolls[8]; y++){
System.out.print("*");
}
}
}
【问题讨论】:
-
为什么不用迭代器
j将所有这些System.out语句包装在一个外部循环中,该迭代器从零运行到 diceRolls 的长度,然后用 j 替换所有显式数字?