这与其他一些答案类似,但对为什么对代码进行更改进行了一些调整和解释。不过,附带说明一下,如果您可以选择正则表达式,请查看 Adi 的答案。他为您提供了另一种解决问题的方法,但是由于这是家庭作业,因此不确定它是否是可行的解决方案。无论如何,有解释(跳到最终产品的底部):
更改您声明开始的内容
int vowelCount = 0;
// All the Strings/StringBuilders can be final since we will never reinstantiate them
final String defParagraph = "This is an example sentence.";
// We'll just make a lowercase version here. That way we don't
// .toLowerCase() everytime though the loop, and for people that complain
// about trying to optimize - I think it's easier to read too.
final String lowerCaseVersion = defParagraph.toLowerCase();
// Declare the stringBuilder with the size of defParagraph. That is the
// maximum size the vowel-less text could be, and ensures the stringBuilder
// won't overflow it's initial capacity and have to waste time growing.
final StringBuilder newParagraph = new StringBuilder(defParagraph.length());
// Not using the vowel array. We will remove the loop
// and just || them together - see below
//char[] vowels = {'a', 'e', 'i', 'o', 'u'};
// You didn't need sbParagraph for anything you had (defParagraph works fine).
// Also, you could have just been a regular String since you never changed it.
//StringBuilder sbParagraph = new StringBuilder(defParagraph);
// Don't need vowParagraph since we aren't tracking the actual vowels, just the count
//StringBuilder vowParagraph = new StringBuilder("");
对实际循环的更改
for (int i = 0; i < lowerCaseVersion.length(); i++) {
// grab the current character
char tempChar = lowerCaseVersion.charAt(i);
if ('a' == tempChar || 'e' == tempChar || 'i' == tempChar
|| 'o' == tempChar || 'u' == tempChar) {
// It matched one of the vowels, so count it
vowelCount ++;
} else {
// It didn't match a vowel, so add it the consonants stringBuilder
// Oh, and append a character from the original, not the lowerCaseVersion
newParagraph.append(defParagraph.charAt(i));
}
}
然后一起没有评论:
int vowelCount = 0;
final String defParagraph = "This is an example sentence.";
final String lowerCaseVersion = defParagraph.toLowerCase();
final StringBuilder newParagraph = new StringBuilder(defParagraph.length());
System.out.println("Characters: " + defParagraph.length());
for (int i = 0; i < lowerCaseVersion.length(); i++) {
char tempChar = lowerCaseVersion.charAt(i);
if ('a' == tempChar || 'e' == tempChar || 'i' == tempChar
|| 'o' == tempChar || 'u' == tempChar) {
vowelCount ++;
} else {
newParagraph.append(defParagraph.charAt(i));
}
}
System.out.println("\tVowel: " + vowelCount);
System.out.println("\tDefPara: " + defParagraph.toString());
System.out.println("\tNewPara: " + newParagraph.toString());
输出如下:
Characters: 28
Vowels: 9
DefPara: This is an example sentence.
NewPara: Ths s n xmpl sntnc.
笔记
- 在这种情况下,使用
final
确实是可选的。我倾向于尽可能使用它,但这可能是个人喜好。这个问题有一些关于何时使用的讨论final
,可能值得一试。