Dice.java.html

  1  import java.util.Scanner;
  2  
  3  /**
  4     This program reads a sequence of die toss values and prints how many times
  5     each value occurred.
  6  */
  7  public class Dice
  8  {
  9     private int[] counters;
 10     
 11     public Dice(int sides)
 12     {
 13        counters = new int[sides + 1]; // counters[0] is not used
 14     }
 15  
 16     public void countInputs()
 17     {
 18        System.out.println("Please enter values, Q to quit:");
 19        Scanner in = new Scanner(System.in);
 20        while (in.hasNextInt())
 21        {  
 22           int value = in.nextInt();
 23  
 24           // Increment the counter for the input value
 25  
 26           if (1 <= value && value <= counters.length)
 27           {
 28              counters[value]++;
 29           }
 30           else
 31           {
 32              System.out.println(value + " is not a valid input.");
 33           }
 34        }
 35     }
 36  
 37     public void printCounters()
 38     {
 39        for (int i = 1; i < counters.length; i++)
 40        {
 41           System.out.printf("%2d: %4d\n", i, counters[i]);
 42        }      
 43     }
 44  }
 45