Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit2e0a01a

Browse files
author
jsquared21
committed
Add Ex 21.6
1 parent02d2b7b commit2e0a01a

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed
Binary file not shown.
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
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+
importjava.util.*;
10+
11+
publicclassExercise_21_06 {
12+
publicstaticvoidmain(String[]args) {
13+
// Create a Scanner
14+
Scannerinput =newScanner(System.in);
15+
16+
// Create a list and two sets
17+
List<Integer>list =newLinkedList<>();// Stores all integers
18+
TreeSet<Integer>set =newTreeSet<>();// Stores nonduplicate integers
19+
Set<Integer>results =newHashSet<>();// Stores results
20+
21+
// Prompt the user to enter a number of integers
22+
System.out.println("Enter a number of integers."
23+
+"\nInput ends when the input is 0:");
24+
25+
intinteger;
26+
while ((integer =input.nextInt()) !=0) {
27+
list.add(integer);
28+
set.add(integer);
29+
}
30+
31+
// Find the maximum occurrence
32+
intmax =0;
33+
for (Integeri:set) {
34+
intfrequency =Collections.frequency(list,i);
35+
if (frequency >max)
36+
max =frequency;
37+
}
38+
39+
// Add integers with the most occurrences to list
40+
for (Integeri: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+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp