1
+ /**********************************************************************************
2
+ * (Count the occurrences of numbers entered) Write a program that reads an *
3
+ * unspecified number of integers and finds the one that has the most occurrences. *
4
+ * The input ends when the input is 0. For example, if you entered 2 3 40 3 5 4 –3 *
5
+ * 3 3 2 0, the number 3 occurred most often. If not one but several numbers have *
6
+ * the most occurrences, all of them should be reported. For example, since 9 and *
7
+ * 3 appear twice in the list 9 30 3 9 3 2 4, both occurrences should be reported. *
8
+ **********************************************************************************/
9
+ import java .util .*;
10
+
11
+ public class Exercise_21_06 {
12
+ public static void main (String []args ) {
13
+ // Create a Scanner
14
+ Scanner input =new Scanner (System .in );
15
+
16
+ // Create a list and two sets
17
+ List <Integer >list =new LinkedList <>();// Stores all integers
18
+ TreeSet <Integer >set =new TreeSet <>();// Stores nonduplicate integers
19
+ Set <Integer >results =new HashSet <>();// Stores results
20
+
21
+ // Prompt the user to enter a number of integers
22
+ System .out .println ("Enter a number of integers."
23
+ +"\n Input ends when the input is 0:" );
24
+
25
+ int integer ;
26
+ while ((integer =input .nextInt ()) !=0 ) {
27
+ list .add (integer );
28
+ set .add (integer );
29
+ }
30
+
31
+ // Find the maximum occurrence
32
+ int max =0 ;
33
+ for (Integer i :set ) {
34
+ int frequency =Collections .frequency (list ,i );
35
+ if (frequency >max )
36
+ max =frequency ;
37
+ }
38
+
39
+ // Add integers with the most occurrences to list
40
+ for (Integer i :set ) {
41
+ if (Collections .frequency (list ,i ) ==max )
42
+ results .add (i );
43
+ }
44
+
45
+ // Display the integers that have the most occurences
46
+ if (results .size () >1 ) {
47
+ System .out .println ("The integers that have the most occurrences are: "
48
+ +results );
49
+ }
50
+ else
51
+ System .out .println ("The integer that has the most occurrences is: "
52
+ +results );
53
+
54
+ }
55
+ }