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 public static void main(String[] args)
10 {
11 int[] counters = countInputs(6);
12 printCounters(counters);
13 }
14
15 /**
16 Reads a sequence of die toss values between 1 and sides (inclusive)
17 and counts how frequently each of them occurs.
18 @return an array whose ith element contains the number of
19 times the value i occurred in the input. The 0 element is unused.
20 */
21 public static int[] countInputs(int sides)
22 {
23 int[] counters = new int[sides + 1]; // counters[0] is not used
24
25 System.out.println("Please enter values, Q to quit:");
26 Scanner in = new Scanner(System.in);
27 while (in.hasNextInt())
28 {
29 int value = in.nextInt();
30
31 // Increment the counter for the input value
32
33 if (1 <= value && value <= sides)
34 {
35 counters[value]++;
36 }
37 else
38 {
39 System.out.println(value + " is not a valid input.");
40 }
41 }
42 return counters;
43 }
44
45 /**
46 Prints a table of die value counters.
47 @param counters an array of counters.
48 counters[0] is not printed.
49 */
50 public static void printCounters(int[] counters)
51 {
52 for (int j = 1; j < counters.length; j++)
53 {
54 System.out.println(j + ": " + counters[j]);
55 }
56 }
57 }
58