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

Commit066d8bf

Browse files
author
jsquared21
committed
Ex 21.8
1 parent0c35a9c commit066d8bf

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed
2.69 KB
Binary file not shown.
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/*********************************************************************************
2+
* (Count the occurrences of words in a text file) Rewrite Listing 21.9 to read *
3+
* the text from a text file. The text file is passed as a command-line argument. *
4+
* Words are delimited by whitespace characters, punctuation marks (,;.:?), *
5+
* quotation marks ('"), and parentheses. Count words in case-insensitive fashion *
6+
* (e.g., consider Good and good to be the same word). The words must start with *
7+
* a letter. Display the output in alphabetical order of words, with each word *
8+
* preceded by its occurrence count. *
9+
*********************************************************************************/
10+
importjava.util.*;
11+
importjava.io.*;
12+
13+
publicclassExercise_21_08 {
14+
publicstaticvoidmain(String[]args)throwsException {
15+
// Check command-line argument length
16+
if (args.length !=1) {
17+
System.out.println("Usage: java Exercise_21_08 textFileName");
18+
System.exit(1);
19+
}
20+
21+
// Check if the file exists
22+
Filefile =newFile(args[0]);
23+
if (!file.exists()) {
24+
System.out.println("The file " +args[0] +" does not exists.");
25+
System.exit(1);
26+
}
27+
28+
// Create a TreeMap to hold words as key and count as value
29+
Map<String,Integer>map =newTreeMap<>();
30+
31+
try (// Create an input stream
32+
Scannerinput =newScanner(file);
33+
) {
34+
while (input.hasNext()) {
35+
String[]words =input.nextLine().split("[\n\t\r\"\'.,;:!?()]");
36+
store(map,words);
37+
}
38+
}
39+
40+
// Get all entries into a set
41+
Set<Map.Entry<String,Integer>>entrySet =map.entrySet();
42+
43+
// Get key and value from each entry
44+
for (Map.Entry<String,Integer>entry:entrySet)
45+
System.out.println(entry.getValue() +"\t" +entry.getKey());
46+
}
47+
48+
/** Method Sotres occurrence of words */
49+
privatestaticvoidstore(Map<String,Integer>map,String[]words) {
50+
for (inti =0;i <words.length;i++) {
51+
Stringkey =words[i].toLowerCase();
52+
53+
if (key.length() >0 &&Character.isLetter(key.charAt(0))) {
54+
if (!map.containsKey(key)) {
55+
map.put(key,1);
56+
}
57+
else {
58+
intvalue =map.get(key);
59+
value++;
60+
map.put(key,value);
61+
}
62+
}
63+
}
64+
}
65+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp