Advertisement
Didart

Count Character Types

Jan 26th, 2023 (edited)
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.24 KB | None | 0 0
  1. package StreamsFilesAndDirectories4;
  2.  
  3. import java.io.BufferedWriter;
  4. import java.io.FileWriter;
  5. import java.io.IOException;
  6. import java.nio.file.Files;
  7. import java.nio.file.Path;
  8. import java.util.HashSet;
  9. import java.util.List;
  10. import java.util.Set;
  11.  
  12. public class CountCharacterTypes {
  13.     public static void main(String[] args) throws IOException {
  14.  
  15.         int vowelsCount = 0;
  16.         int punctuationCount = 0;
  17.         int consonantsCount = 0;
  18.        
  19.         Set<Character> vowels = getVowels();
  20.         Set<Character> punctuationalMarks = getPuntMarks();
  21.  
  22.         String path = "C:\\Users\\User\\Desktop\\Java Advanced - 10.01.23 - 13.09.22\\src\\StreamsFilesAndDirectories4\\04. Java-Advanced-Files-and-Streams-Exercises-Resources\\input.txt";
  23.         List<String> allLines = Files.readAllLines(Path.of(path));
  24.  
  25.         for (String line : allLines) {
  26.             for (int index = 0; index < line.length(); index++) {
  27.                 char currentSymbol = line.charAt(index);
  28.                 if (currentSymbol == ' ') {
  29.                     continue;
  30.                 }
  31.                
  32.                 if (vowels.contains(currentSymbol)) {
  33.                     vowelsCount++;
  34.                 } else if (punctuationalMarks.contains(currentSymbol)) {
  35.                     punctuationCount++;
  36.                 } else {
  37.                     consonantsCount++;
  38.                 }
  39.             }
  40.         }
  41.        
  42.         BufferedWriter writer = new BufferedWriter(new FileWriter("output_4.txt"));
  43.         writer.write("Vowels: " + vowelsCount);
  44.         writer.newLine();
  45.         writer.write("Other symbols: " + consonantsCount);
  46.         writer.newLine();
  47.         writer.write("Punctuation: " + punctuationCount);
  48.         writer.close();
  49.  
  50.     }
  51.  
  52.     private static Set<Character> getPuntMarks() {
  53.         Set<Character> marks = new HashSet<>();
  54.         marks.add('!');
  55.         marks.add('?');
  56.         marks.add('.');
  57.         marks.add(',');
  58.         return marks;
  59.     }
  60.  
  61.     private static Set<Character> getVowels() {
  62.         Set<Character> vowels = new HashSet<>();
  63.         vowels.add('a');
  64.         vowels.add('e');
  65.         vowels.add('i');
  66.         vowels.add('o');
  67.         vowels.add('u');
  68.         return vowels;
  69.  
  70.     }
  71. }
  72.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement