Advertisement
alyoshinkkaa

Untitled

Jul 29th, 2023
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.74 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.BufferedWriter;
  3. import java.io.FileInputStream;
  4. import java.io.InputStreamReader;
  5. import java.io.Reader;
  6. import java.io.IOException;
  7. import java.io.OutputStreamWriter;
  8. import java.io.FileOutputStream;
  9. import java.lang.String;
  10. import java.util.LinkedHashMap;
  11. import java.util.Map;
  12.  
  13. public class WordStatInput {
  14. public static void addWord(Map<String, Integer> words, String word) {
  15. if (word.length() > 0) {
  16. // :NOTE: extra action -- read documentation about Map and .putIfAbsent()
  17. words.putIfAbsent(word, words.getOrDefault(word, 0));
  18. words.replace(word, words.get(word), words.get(word) + 1);
  19. }
  20. }
  21. public static void main(String[] args){
  22. Map<String, Integer> words = new LinkedHashMap<>();
  23. try {
  24. Reader reader = new BufferedReader(new InputStreamReader(
  25. new FileInputStream(args[0])
  26. ));
  27. try {
  28. char symbol;
  29. StringBuilder word = new StringBuilder();
  30. int read = reader.read();
  31. symbol = (char) read;
  32. while (read > -1) {
  33. if (Character.isLetter(symbol) || symbol == '\'' || Character.DASH_PUNCTUATION == Character.getType(symbol)) {
  34. word.append(symbol);
  35. } else {
  36. addWord(words, word.toString().toLowerCase());
  37. word.delete(0, word.length());
  38. }
  39. read = reader.read();
  40. symbol = (char) read;
  41. }
  42. addWord(words, word.toString().toLowerCase());
  43. } finally {
  44. reader.close();
  45. }
  46. // :NOTE: you already catch IOException, why do you add "try" here?
  47. try {
  48. BufferedWriter writer = new BufferedWriter(
  49. new OutputStreamWriter(
  50. new FileOutputStream(args[1])
  51. )
  52. );
  53. try {
  54. for (Map.Entry<String, Integer> output : words.entrySet()) {
  55. writer.write(output.getKey() + " " + output.getValue() + System.lineSeparator());
  56. }
  57. } finally {
  58. writer.close();
  59. }
  60. } catch (IOException e) {
  61. System.out.println("I/O Exception: " + e.getMessage());
  62. }
  63. // :NOTE: it's better to clarify the exception with the file missing to the user, if it occurs
  64. } catch (IOException e) {
  65. System.out.println("I/O Exception: " + e.getMessage());
  66. }
  67. }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement