Programming Assignment Unit 1
Programming Assignment Unit 1
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
// User Input
System.out.println("Please enter a paragraph or a lengthy text:");
String text = scanner.nextLine();
// Character Count
int charCount = text.length();
System.out.println("Total number of characters: " + charCount);
// Word Count
String[] words = text.split("\\s+");
int wordCount = words.length;
System.out.println("Total number of words: " + wordCount);
// Character Frequency
System.out.println("Please enter a character to find its frequency:");
char characterToFind = scanner.next().charAt(0);
int charFrequency = findCharacterFrequency(text, characterToFind);
System.out.println("Frequency of '" + characterToFind + "': " + charFrequency);
// Word Frequency
System.out.println("Please enter a word to find its frequency:");
scanner.nextLine(); // consume the leftover newline
String wordToFind = scanner.nextLine();
int wordFrequency = findWordFrequency(words, wordToFind);
System.out.println("Frequency of \"" + wordToFind + "\": " + wordFrequency);
// Unique Words
int uniqueWordsCount = findUniqueWordsCount(words);
System.out.println("Number of unique words: " + uniqueWordsCount);
scanner.close();
}
return mostCommonChar;
}
Explanation:
1. User Input: The program first prompts the user to input a paragraph or lengthy text and
stores it.
2. Character Count: The length of the text is calculated using text.length().
3. Word Count: The text is split into words using split("\\s+"), and the length of the
resulting array gives the word count.
4. Most Common Character: A frequency map is built for all characters, and the most
frequent character is found.
5. Character Frequency: The program prompts the user to enter a character and calculates
its frequency in the text.
6. Word Frequency: The program prompts the user to enter a word and calculates its
frequency in the text.
7. Unique Words: A frequency map is built for all words, and the number of unique words
is determined.
Screenshot: