文字列を解析する LineParser というクラスを作成できます。get および set メソッドを使用して変数にアクセスすることを常にお勧めします。
class LineParser {
public int numberOfVowels;
public int numberOfConsonents;
public int numberOfSpaces;
public int numberOfSpecialChars;
public int numberOfWords;
public int numberOfDigits;
public LineParser(String str) {
ProcessStr(str);
}
//Parses a string to count number of vowels, consonents, spaces,
//special characters and words,
//Treates non letter chars as word terminators.
//So London2Paris contains 2 words.
private void ProcessStr(String str) {
boolean wordend = false;
char[] word = new char[str.length()];
int wordIndex = 0;
for (char c : str.toCharArray()){
if (Character.isLetterOrDigit(c)){
if (Character.isLetter(c)) {
word[wordIndex++] = c;
c = Character.toLowerCase(c);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'){
numberOfVowels ++;
}
else {
numberOfConsonents ++;
}
}
else {
numberOfDigits++;
wordend = true;
}
}
else if (Character.isWhitespace(c)) {
numberOfSpaces ++;
wordend = true;
}
else {
numberOfSpecialChars ++;
wordend = true;
}
if (wordend == true && wordIndex > 0){
numberOfWords ++;
wordIndex = 0;
wordend = false;
}
}
wordend = true;
if (wordend == true && wordIndex > 0){
numberOfWords ++;
}
}
}
このクラスは、このようにメイン関数から使用できます
public static void main(String args[])throws IOException
{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the String:");
String text = bf.readLine();
LineParser parser = new LineParser(text);
System.out.println("There are" + " " + parser.numberOfVowels + " " + "vowels");
System.out.println("There are" + " " + parser.numberOfConsonents + " " + "Consonents");
System.out.println("There are" + " " + parser.numberOfSpaces + " " + "Spaces");
System.out.println("There are" + " " + parser.numberOfSpecialChars + " " + "SpecialChars");
System.out.println("There are" + " " + parser.numberOfWords + " " + "Words");
}