Touchpad
Touchpad

Reputation: 29

java read vowels from text file

I'm creating a program that reads vowels from a text file. The text is a paragraph long and I want the program to count the vowels per sentence.

So this is an example 7 vowels

Another 3 vowels

So far I've written the code to be able to read vowels. Though, it reads it as an additional whole. In the loop it will count 7 first then the second line would output it as 10. I want it to output 7 as first line and 3 as second line.

I'm looking at the String API from java and I don't see anything that can help solve this. The way I'm currently counting the vowels is having a for loop to loop through with Charat(). Am I missing something or is there no way to stop it from reading and adding to the counter?

Here's an example

    while(scan.hasNext){
      String str = scan.nextLine();
      for(int i = 0; i<str.length(); i++){
        ch = str.charAt(i);
        ...
        if(...)
          vowel++;
        }//end for
      S.O.P();
        vowel = 0;//This is the answer... Forgotten that java is sequential...
      }

    }// end main()
  }//end class

  /*output:
  This sentence have 7 vowels.
  This sentence have 3 vowels.
  */

Upvotes: 2

Views: 5129

Answers (3)

stackoverflowuser2010
stackoverflowuser2010

Reputation: 40969

Here is a complete example to count the number of vowels in each sentence of a file. It uses some advanced techniques: (1) a regular expression to split paragraphs into sentences; and (2) a HashSet data structure to quickly check if a character is a vowel. The program assumes that each line in the file is a paragraph.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class CountVowels {

    // HashSet of vowels to quickly check if a character is a vowel.
    // See usage below.
    private Set<Character> vowels =
        new HashSet<Character>(Arrays.asList('a', 'e', 'i', 'o', 'u', 'y'));

    // Read a file line-by-line. Assume that each line is a paragraph.
    public void countInFile(String fileName) throws IOException {

        BufferedReader br = new BufferedReader(new FileReader(fileName));
        String line;

        // Assume one file line is a paragraph.
        while ((line = br.readLine()) != null) {
            if (line.length() == 0) {
                continue; // Skip over blank lines.
            }
            countInParagraph(line);
        }

        br.close();
    }

    // Primary function to count vowels in a paragraph. 
    // Splits paragraph string into sentences, and for each sentence,
    // counts the number of vowels.
    private void countInParagraph(String paragraph) {

        String[] sentences = splitParagraphIntoSentences(paragraph);

        for (String sentence : sentences) {
            sentence = sentence.trim(); // Remove whitespace at ends.
            int vowelCount = countVowelsInSentence(sentence);
            System.out.printf("%s : %d vowels\n", sentence, vowelCount);
        }
    }

    // Splits a paragraph string into an array of sentences. Uses a regex.
    private String[] splitParagraphIntoSentences(String paragraph) {
        return paragraph.split("\n|((?<!\\d)\\.(?!\\d))");
    }

    // Counts the number of vowels in a sentence string.
    private int countVowelsInSentence(String sentence) {

        sentence = sentence.toLowerCase();

        int result = 0;    
        int sentenceLength = sentence.length();

        for (int i = 0; i < sentenceLength; i++) {
            if (vowels.contains(sentence.charAt(i))) {
                result++;
            }
        }

        return result;
    }

    // Entry point into the program.
    public static void main(String argv[]) throws IOException {

        CountVowels cw = new CountVowels();

        cw.countInFile(argv[0]);
    }
}

For this file example.txt:

So this is an example. Another.

This is Another line.

Here is the result:

% java CountVowels example.txt
So this is an example : 7 vowels
Another : 3 vowels
This is Another line : 7 vowels

Upvotes: 1

ShadowGod
ShadowGod

Reputation: 7981

Maybe not the most elegant way but real quick to count vowels in each sentence I came up with this, tested and works (at least with my test string):

String testString = ("This is a test string. This is another sentence. " +
            "This is yet a third sentence! This is also a sentence?").toLowerCase();
    int stringLength = testString.length();
    int totalVowels = 0;
    int i;

        for (i = 0; i < stringLength - 1; i++) {
            switch (testString.charAt(i)) {
                case 'a':
                case 'e':
                case 'i':
                case 'o':
                case 'u':
                    totalVowels++;
                    break;
                case '?':
                case '!':
                case '.':
                    System.out.println("Total number of vowels in sentence: " + totalVowels);
                    totalVowels = 0;
            }

        }

    System.out.println("Total number of vowels in last sentence: " + totalVowels);

Upvotes: 1

Donald Taylor
Donald Taylor

Reputation: 62

I created a simple class to achieve what I believe your goal is. The vowelTotal resets so that you don't have the issue you mentioned of the sentences' vowels adding to each other. I'm assuming that by looking at my code, you can see the solution to your own? Also, this code assumes you include "y" as a vowel and it also assumes the sentences end with proper punctuation.

public class CountVowels{
    String paragraph;
    public CountVowels(String paragraph){
        this.paragraph = paragraph;
        countVowels(paragraph);
    }

    int vowelTotal = 0;
    int sentenceNumber = 0;
    public void countVowels(String paragraph){
        for(int c = 0; c < paragraph.length(); c++){
            if( paragraph.charAt(c) == 'a' || paragraph.charAt(c) == 'e' || paragraph.charAt(c) == 'i' || paragraph.charAt(c) == 'o' || paragraph.charAt(c) == 'u' || paragraph.charAt(c) == 'y'){
                vowelTotal++; //Counts a vowel
            } else if( paragraph.charAt(c) == '.' || paragraph.charAt(c) == '!' || paragraph.charAt(c) == '?' ){
                sentenceNumber++; //Used to tell which sentence has which number of vowels
                System.out.println("Sentence " + sentenceNumber + " has " + vowelTotal + " vowels.");
                vowelTotal = 0; //Resets so that the total doesn't keep incrementing
            }
        }
    }
}

Upvotes: 2

Related Questions