您可以编写一个名为 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");
}