我想根据滚动骰子的次数(全部通过数组)打印星号。我在星号之前遇到了骰子面(i)印刷的问题。另外,我从零开始得到两个零,并且不知道它们来自哪里。 我会很感激的帮助。Java:数组星号打印的值
我的代码:
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
根据@Paul评论,这是'0 0'来自哪里,你开始'i = 0',这没有价值,因此你得到'0 0' –
我认为你的潜在挑战因为java中的数组是基于零的,但你有点像对待它们一样。换句话说,数组的第一个元素位于索引0处,因此您应该将索引处的索引值设置为1。另外,使用'System.out.print(“some string”);'后面紧跟'System.out .println();'有点笨重。取而代之,使用'System.out.println(“some string”);' – Taylor