public class Text{
private StringBuffer text;
private int numLines = 0; // Anzahl Zeilen
private int numWords = 0; // Anzahl Wörter
private int numLetters = 0; // Anzahl Buchstaben
private int numPunctuations = 0; // Anzahl Satzzeichen
private int numCharacters = 0; // Anzahl (beliebiger) Zeichen
public Text(String str){
this.text = new StringBuffer(str);
this.count();
}
// Bestimmt, ob c ein Kleinbuchstabe ist
private static boolean isLowerCaseLetterP(char c){
return ((c >= 'a') && (c <= 'z'));
}
// Bestimmt, ob c ein Grossbuchstabe ist
private static boolean isUpperCaseLetterP(char c){
return ((c >= 'A') && (c <= 'Z'));
}
// Bestimmt, ob c ein Satzzeichen ist
private static boolean isPunctuationMark(char c){
char[] satzzeichen = {',','.','!','?',':',';','"','-'};
boolean istSatzzeichen = false;
int i=0;
while ((i<satzzeichen.length) && (!istSatzzeichen)){
if (satzzeichen[i] == c){
istSatzzeichen = true;
}
i++;
}
return istSatzzeichen;
}
/* *** Aufgabenteil (a) *** */
private void count(){
//AnzahlZeilen
for(int i=0;i<text.length();i++)
{
if(text.charAt(i) == '\n')
{
numLines++;
numWords++;
numCharacters++;
}
if(text.charAt(i) == ' ')
{
numWords++;
numCharacters++;
}
if(isLowerCaseLetterP(text.charAt(i)) == true || isUpperCaseLetterP(text.charAt(i)) == true)
{
numLetters++;
numCharacters++;
}
if(isPunctuationMark(text.charAt(i)) == true)
{
numPunctuations++;
numCharacters++;
}
}
}
/* *** Aufgabenteil (b) *** */
// Methode removePunctuationsAndReplaceNewlines
public StringBuffer removePunctuationsAndReplaceNewlines()
{
StringBuffer sb = new StringBuffer(this.text.toString());
for(int i=0; i<sb.length()-1;i++)
{
if(isPunctuationMark(sb.charAt(i)) == true)
{
sb.deleteCharAt(i);
}
if(sb.charAt(i) == '\n')
{
sb.setCharAt(i,' ');
}
}
return sb;
}
/* *** Aufgabenteil (c) *** */
// Methode filterWords
public void filterWords()
{ int from = 0;
int to = 0;
StringBuffer temp = removePunctuationsAndReplaceNewlines();
int[] wordCount = new int[49];
double avg = 0;
int arrayCount=0;
for(int i=0; i<temp.length()-1;i++)
{
to = temp.toString().indexOf(' ',from);
int wordLength = to - from;
wordCount[wordLength]++;
from = to++;
}
for(int i=0; i<wordCount.length;i++)
{
avg += i * wordCount[i];
}
for(int i=0;i<wordCount.length;i++)
{
if(wordCount[i]!=0)
{
arrayCount++;
}
}
avg = avg/arrayCount;
System.out.println("Mittlere Wortlaenge: " +avg);
}
public String toString(){
return ("Anzahl Zeilen: " + numLines +
"\nAnzahl Woerter: " + numWords +
"\nAnzahl Buchstaben: " + numLetters +
"\nAnzahl Satzzeichen: " + numPunctuations +
"\nAnzahl Zeichen: " + numCharacters);
}
public static void main(String[] args){
System.out.println("Text 1: ");
Text text1 = new Text(TextReader.readFile("Text1.txt"));
System.out.println(text1);
text1.filterWords();
System.out.println("\n***************\n");
System.out.println("Text 2: ");
Text text2 = new Text(TextReader.readFile("Text2.txt"));
System.out.println(text2);
text2.filterWords();
}
}