2016-11-09 100 views
0

我想打印的星星數量等於給定數字1到6的滾動次數。然後把它放到一個數組中,這樣我就可以在System.out的中間打印給定數量的恆星。 它是這樣的[1] ******************* 19Java直方圖,如何將星星添加到數組

我已經有基本代碼在這裏

import java.util.Random; 
public class Program7 { 

    public static void main(String[] args) { 
     Random ran = new Random(); 
     int [] timesRolled = new int[7]; 
     for (int i=0;i<100;i++){ 
      int die= ran.nextInt(6)+1;   
      if (die==1){ 
       timesRolled [1]++; 
       System.out.print("*"); 
      } 
      if (die==2){ 
       timesRolled [2]++; 
       System.out.print("*"); 
      } 
      if (die==3){ 
       timesRolled [3]++; 
       System.out.print("*"); 
      } 
      if (die==4){ 
       timesRolled [4]++; 
       System.out.print("*"); 
      } 
      if (die==5){ 
       timesRolled [5]++; 
       System.out.print("*"); 
      } 
      if (die==6){ 
       timesRolled [6]++; 
       System.out.print("*"); 
      } 
     } 
     System.out.println("[1]" + "\t" + here is where i want the stars + timesRolled [1]); 
     System.out.println("[2]" + "\t" + timesRolled [2]); 
     System.out.println("[3]" + "\t" + timesRolled [3]); 
     System.out.println("[4]" + "\t" + timesRolled [4]); 
     System.out.println("[5]" + "\t" + timesRolled [5]); 
     System.out.println("[6]" + "\t" + timesRolled [6]); 
    } 

} 
+2

[HISTOGRAM(Array = Stars Output)]的可能重複(http://stackoverflow.com/questions/33029885/histogram-array-stars-output) –

回答

-1

試試這個,

import java.util.Random; 

public class Program7 { 

    public static void main(String[] args) { 
     Random ran = new Random(); 
     int[] timesRolled = new int[7]; 
     for (int i = 0; i < 100; i++) { 
      int die = ran.nextInt(6) + 1; 
      if (die == 1) { 
       timesRolled[1]++;     
      } 
      if (die == 2) { 
       timesRolled[2]++;    
      } 
      if (die == 3) { 
       timesRolled[3]++;     
      } 
      if (die == 4) { 
       timesRolled[4]++; 
      } 
      if (die == 5) { 
       timesRolled[5]++; 
      } 
      if (die == 6) { 
       timesRolled[6]++; 
      } 
     } 
     for (int i = 1; i < timesRolled.length; i++) { 
      int j = timesRolled[i]; 
      String stars = ""; 
      for (int k = 0; k < j; k++) { 
       stars += "*"; 
      } 
      System.out.println("[" + i + "]" + "\t" + stars + " " + timesRolled[i]); 
     } 
    } 
}