【发布时间】:2023-03-28 13:26:01
【问题描述】:
我正在尝试根据掷骰子的次数(全部通过数组)打印星号。我遇到了在星号之前打印骰子面(i)的问题。另外,我突然得到两个零,不知道它们来自哪里。 非常感谢您的帮助。
我的代码:
public class Histogram {
public static void main(String[] args) {
// TODO Auto-generated method stub
int numRoles = 100;
int[] amountRoles = new int[7]; // amountRoles Holds the array
for (int i = 1; i < 7; i++)
amountRoles[i] = 0; // Set 0
{
for (int i = 0; i < numRoles; i++)
{
int die1 = (int)(Math.random()*6+1);
amountRoles[die1]++; // Increments
}
System.out.println("The die was rolled " + numRoles + " times, its six value's counts are:");
for (int i = 1; i < 7; i++)
{
System.out.print("Side " + i + " was rolled " + amountRoles[i]+ " times out of " + numRoles + ".");
// Prints each sides value (i) alongside with how many times it was rolled (amountRoles[i]).
System.out.println(); // Formatting Line
}
}
for (int i = 0; i < amountRoles.length; i++) // Iterates through amountRoles
{
for(int j = 0; j < amountRoles[i]; j++) // Loop through amountRoles[i]
{
System.out.print("" + "*");
}
System.out.println(i + " " + amountRoles[i]);
}
}
}
我的输出:
The die was rolled 100 times, its six value's counts are:
Side 1 was rolled 11 times out of 100.
Side 2 was rolled 19 times out of 100.
Side 3 was rolled 19 times out of 100.
Side 4 was rolled 17 times out of 100.
Side 5 was rolled 16 times out of 100.
Side 6 was rolled 18 times out of 100.
0 0 (Where are these zeroes coming from?)
***********1 11
*******************2 19
*******************3 19
*****************4 17
****************5 16
******************6 18
我的目标示例输出:
[1] ******************* 19
[2] ************ 12
[3] ********************* 21
[4] ******************** 20
[5] ************* 13
[6] *************** 15
【问题讨论】:
-
提示:为什么需要一个大小为 7 的数组来保存 6 面骰子掷出特定结果的次数?
-
根据@Paul 的评论,这就是
0 0的来源,你从i = 0开始,它没有任何价值,因此你得到0 0 -
我认为你面临的潜在挑战是java中的数组是从零开始的,但你有点像对待它们一样对待它们。换句话说,数组的第一个元素位于索引 0 处,因此您应该将 1 的滚动计数放在索引 0 处。此外,使用
System.out.print("some string");后跟System.out.println();有点笨拙。而是使用System.out.println("some string");
标签: java arrays for-loop iteration