In java language. Read the text from a Web page. The URL for the Web page is pas
ID: 3903548 • Letter: I
Question
In java language.
Read the text from a Web page. The URL for the Web page is passed as an argument.
Words are delimited by whitespace, punctuation marks (,;.:?), quotation marks (’”), and parentheses.
Count words in case-insensitive fashion (e.g., consider Good and good to be the same word).
The words must start with a letter.
Display the output in alphabetical order of words with each word preceded by its occurrence count.
Test your program with the input URL "www.google.com"
Here is a sample run:
Input URL: https://www.google.com
Display words and their count in ascending order of the words
48 a
1 agen
2 all
2 amp
1 and
1 appendchild
1 apply
3 arial
...
Explanation / Answer
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class CountWordsFile{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the file path: ");
File file = new File(scanner.next());
if (!file.isFile()) {
System.out.println(file + " is not a file.");
}
String[] words;
try (BufferedReader in = new BufferedReader(new FileReader(file))) {
StringBuilder buffer = new StringBuilder(10000);
String s;
while ((s = in.readLine()) != null)
buffer.append(s).append(" ");
words = buffer.toString().split("[0-9]+|\W+");
} catch (IOException ex) {
words = new String[1];
System.out.println("Error opening file...");
System.exit(0);
}
// To Create a TreeMap to hold words as key and count as value
Map<String, Integer> map = new TreeMap<>();
for (String word1 : words) {
String key = word1.toLowerCase();
if (key.length() > 0) {
if (!map.containsKey(key)) {
map.put(key, 1);
} else {
int value = map.get(key);
value++;
map.put(key, value);
}
}
}
map.forEach((k, v) -> System.out.println(k + " " + v));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.