2016-09-26 31 views
2

Ich erstelle ein Programm, das Vokale aus einer Textdatei liest. Der Text ist ein Absatz lang und ich möchte, dass das Programm die Vokale pro Satz zählt.Java lesen Vokale aus Textdatei

So ist dies ein Beispiel 7 Vokale

Weitere 3 Vokale

Bisher habe ich den Code geschrieben habe in der Lage sein, Vokale zu lesen. Allerdings liest es sich als zusätzliches Ganzes. In der Schleife zählt es zuerst 7, dann würde die zweite Zeile es als 10 ausgeben. Ich möchte, dass es 7 als erste Zeile und 3 als zweite Zeile ausgibt.

Ich schaue auf die String-API von Java und ich sehe nichts, das dazu beitragen kann, dies zu lösen. Die Art und Weise, wie ich die Vokale zähle, hat eine for-Schleife, die mit Charat() durchlaufen wird. Fehle ich etwas oder gibt es keine Möglichkeit, das Lesen und Hinzufügen zum Schalter zu stoppen?

Hier ist ein Beispiel

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. 
    */ 
+0

Können Sie Ihren Code schreiben? –

+0

Warum postest du deinen Code nicht? – passion

+0

Möchten Sie, dass es pro Satz oder pro Zeile zählt? – afsafzal

Antwort

2

ich eine einfache Klasse geschaffen zu erreichen, was ich glaube, Ihr Ziel ist. Der VokalTotal wird zurückgesetzt, sodass Sie das von Ihnen erwähnte Problem der Vokale der Sätze nicht mehr hinzufügen können. Ich gehe davon aus, dass Sie, wenn Sie sich meinen Code anschauen, die Lösung für sich selbst sehen können? In diesem Code wird außerdem davon ausgegangen, dass Sie "y" als Vokal einbeziehen. Außerdem wird davon ausgegangen, dass die Sätze mit der richtigen Interpunktion enden.

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 
      } 
     } 
    } 
} 
+0

Es gibt eine andere wichtige Annahme, die Sie machen. Versuchen Sie es in diesem Absatz: "Ich habe meiner Professorin, Dr. Black, meine Lösung gezeigt, aber sie hat mir gesagt, dass es ein Problem damit gibt." – ajb

+0

Wow, daran hatte ich nicht gedacht. Danke, dass du es aufgezeigt hast. –

+0

Ja - aber ich weiß wirklich keine gute Lösung, ausser anzunehmen, dass es keine Abkürzungen gibt. – ajb

1

Vielleicht nicht die eleganteste Art, aber ganz schnell zu Vokale in jedem Satz zu zählen kam ich mit diesem nach oben, getestet und funktioniert (zumindest bei meinem 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); 
1

Hier ist ein vollständiges Beispiel, um die Anzahl der Vokale in jedem Satz einer Datei zu zählen. Es verwendet einige fortgeschrittene Techniken: (1) ein regulärer Ausdruck, um Absätze in Sätze aufzuteilen; und (2) eine HashSet-Datenstruktur, um schnell zu überprüfen, ob ein Zeichen ein Vokal ist. Das Programm geht davon aus, dass jede Zeile in der Datei ein Absatz ist.

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]); 
    } 
} 

Für diese Datei example.txt:

So this is an example. Another. 

This is Another line. 

Hier ist das Ergebnis:

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