Touchpad Touchpad - 25 days ago 3x
Java Question

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

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

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

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

This sentence have 7 vowels.
This sentence have 3 vowels.


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;

    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