0% found this document useful (0 votes)
14 views1 page

Problem 3

The Java program reads a text file named 'sample.txt' and counts the frequency of each word, ignoring case and punctuation. It stores the word counts in a HashMap and prints the results to the console. The program handles potential IOExceptions during file reading.

Uploaded by

vineshbaghel10
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views1 page

Problem 3

The Java program reads a text file named 'sample.txt' and counts the frequency of each word, ignoring case and punctuation. It stores the word counts in a HashMap and prints the results to the console. The program handles potential IOExceptions during file reading.

Uploaded by

vineshbaghel10
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

import java.io.

*;
import java.util.*;

public class Problem3 {


public static void main(String[] args) {
String fileName = "sample.txt";
Map<String, Integer> wordCountMap = new HashMap<>();

try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {


String line;

while ((line = br.readLine()) != null) {


line = line.toLowerCase().replaceAll("[^a-zA-Z0-9\\s]", "");
String[] words = line.split("\\s+");

for (String word : words) {


if (!word.isEmpty()) {
wordCountMap.put(word, wordCountMap.getOrDefault(word, 0) + 1);
}
}
}
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
}

System.out.println("Word Frequency Count:");


wordCountMap.forEach((word, count) -> System.out.println(word + ": " + count));
}
}

You might also like