fork download
  1. import java.util.*;
  2.  
  3. class prog {
  4. public static void main(String[] args) {
  5. Scanner scanner = new Scanner(System.in);
  6.  
  7. StringBuilder emailTextBuilder = new StringBuilder();
  8. while (scanner.hasNextLine()) {
  9. String line = scanner.nextLine();
  10. if (line.isEmpty()) {
  11. break;
  12. }
  13. emailTextBuilder.append(line).append(" ");
  14. }
  15. String emailText = emailTextBuilder.toString().trim(); // Eliminarea spațiului final inutil
  16.  
  17. Map<String, Integer> wordCount = new HashMap<>();
  18. String[] words = emailText.split("\\s+");
  19. for (String word : words) {
  20. wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
  21. }
  22.  
  23. String mostFrequentWord = "";
  24. int maxCount = 0;
  25. for (Map.Entry<String, Integer> entry : wordCount.entrySet()) {
  26. String word = entry.getKey();
  27. int count = entry.getValue();
  28. if (count > maxCount || (count == maxCount && word.compareTo(mostFrequentWord) < 0)) {
  29. mostFrequentWord = word;
  30. maxCount = count;
  31. }
  32. }
  33.  
  34. System.out.println(mostFrequentWord);
  35.  
  36. scanner.close();
  37. }
  38. }
  39.  
Success #stdin #stdout 0.14s 54548KB
stdin
Hello! How are you today? It's a sunny day, isn't it? I hope the code can handle special characters like ! and ? without any issues.

stdout
!