我想根據滾動骰子的次數(全部通過數組)打印星號。我在星號之前遇到了骰子面(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