unit 1 java
unit 1 java
*;
while (text.isEmpty()) {
System.out.println("Text cannot be empty. Please enter again:");
text = scanner.nextLine().trim();
}
// Character Count
int charCount = text.length();
System.out.println("\nTotal number of characters: " + charCount);
// Word Count
String[] words = text.trim().split("\\s+");
int wordCount = words.length;
System.out.println("Total number of words: " + wordCount);
// Character Frequency
System.out.print("\nEnter a character to find its frequency: ");
String charInput = scanner.nextLine().trim().toLowerCase();
// Word Frequency
System.out.print("\nEnter a word to find its frequency: ");
String wordInput = scanner.nextLine().trim().toLowerCase();
while (wordInput.isEmpty()) {
System.out.print("Please enter a valid word: ");
wordInput = scanner.nextLine().trim().toLowerCase();
}
int wordFreq = 0;
for (String word : words) {
if (word.toLowerCase().equals(wordInput)) {
wordFreq++;
}
}
System.out.println("Frequency of word \"" + wordInput + "\": " + wordFreq);
// Unique Words
Set<String> uniqueWords = new HashSet<>();
for (String word : words) {
uniqueWords.add(word.toLowerCase());
}
System.out.println("Number of unique words: " + uniqueWords.size());
scanner.close();
}
}