2016-11-11 47 views
1

我無法弄清楚如何根據它們相應的(輸出右側的數字)計數顯示一個舍入數量的星號。Java:循環遍歷和基於四捨五入的打印

我試圖用1個星號來表示100個星號。但是,當我得到一個數字,例如第17卷是417時,我希望它只打印4個星號,而不是5個;相同的四捨五入。我嘗試使用Math.round(),但我沒有成功。

我非常感謝任何幫助。

我的代碼:

public class Histogram { 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 

     int numRoles = 30000; 
     int[] amountRoles = new int[19]; // amountRoles Holds the Array 

     for (int i = 3; i < 7; i++) 
     amountRoles[i] = 0; // Set 0 
     { 
      for (int i = 0; i < numRoles; i++) 
      { 
       int die1 = (int)(Math.random()*6+1); 
       int die2 = (int)(Math.random()*6+1); 
       int die3 = (int)(Math.random()*6+1); 
       amountRoles[die1+die2+die3]++; // Increments 
      } 
      System.out.print("The die was rolled " + numRoles + " times, its six value's counts are:"); 
      for (int i = 3; i < 7; i++) 
      { 
       System.out.println(); // Line Holder 
      } 
     } 
     for (int i = 3; i < amountRoles.length; i++) // Iterates through amountRoles 
     { 
      System.out.print("[" + i + "]" + " "); 
      for(int j = 0; j < amountRoles[i]; j++) // Loop through amountRoles[i] 
      { 
       if (Math.round(j) % 100 == 0) 
       { 
        System.out.print("" + "*"); 
       } 
      } 
      System.out.println(" " + amountRoles[i]); 
     } 
    } 
} 

我的輸出:

[3]  ** 139 
[4]  **** 389 
[5]  ********* 826 
[6]  ************** 1366 
[7]  ********************* 2082 
[8]  ****************************** 2973 
[9]  *********************************** 3440 
[10] *************************************** 3859 
[11] ************************************** 3742 
[12] *********************************** 3482 
[13] ****************************** 2918 
[14] ******************** 1996 
[15] ************** 1341 
[16] ********* 865 
[17] ***** 417 
[18] ** 165 

回答

2

在這裏你打印每行的一部分:你是循環數百次

System.out.print("[" + i + "]" + " "); 
for(int j = 0; j < amountRoles[i]; j++) // Loop through amountRoles[i] 
{ 
    if (Math.round(j) % 100 == 0) 
    { 
     System.out.print("" + "*"); 
    } 
} 
System.out.println(" " + amountRoles[i]); 

。這是不必要和不足的。只要用除法來獲得* S的數量打印:

System.out.print("[" + i + "] "); 
int starsToPrint = (int) Math.round((double) amountRoles[i]/100.0); 
for (int j = 0; j < starsToPrint; j++) { 
    System.out.print("*"); 
} 
System.out.println(" " + amountRoles[i]); 

只是爲了你的信息,你的原代碼被打破的原因是因爲0%100 == 0,所以在你內心的第一次迭代循環它會打印一個額外的「*」。

+0

你在那裏有什麼不處理向上舍入,只是四捨五入。因此,當8是希望時,773會打印7個星號。示例自773> 750以來,圍繞並打印8個星號(742 <750),向下捨去並打印7個星號。 – Aramza

+0

@Aramza啊我明白了。沒問題,這很容易解決。讓我編輯答案。 – nhouser9

1

只需將amountRoles [i]除以100即可。 當然,這不會爲amountRoles [i] < = 50打印任何星號,但我猜這就是你想要的。

for(int j = 0; j < Math.round(amountRoles[i]/100); j++) { // Loop through amountRoles[i] 
     System.out.print("" + "*"); 
    }