2016-11-09 82 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]); 
     } 
    } 
}