问题
I am trying to find a word with the most vowels in a sentence inputted by the user. Right now when I call this method it works fine with a shorter sentence. But when it gets over 7 words it doesn't print out the word with the most vowels. I can't seem to spot the error =(
I thank you guys in advance!
private static void getWordMostVowel(String sentence) {
String word = "";
String wordMostVowel = "";
int temp = 0;
int vowelCount = 0;
char ch;
for(int i = 0; i < sentence.length(); i++){
ch = sentence.charAt(i);
sentence = sentence.toLowerCase();
if (ch != ' '){
word = word + ch;
if ( ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' )
vowelCount++;
}
else {
if(vowelCount > temp){
temp = vowelCount;
wordMostVowel = word;
}
word = " ";
}
}
System.out.println("The word with the most vowels is: " + " " + wordMostVowel);
}
回答1:
I suggest a different solution: don't try to "build" the words manually; that adds a lot of unnecessary complexity to your code.
Instead, go for:
String words[] = sentence.split(" ");
The above creates an array of your words (assuming that your input simply uses spaces between each word).
From there you can do something like:
Set<Character> vowels = new HashSet<T>(Arrays.asList('a', 'e' ...));
The above creates a set that contains all vowels.
Now:
for (String oneWord : words) {
int vowelCount = 0;
for (int i=0; i< oneWord.length; i++) {
if (vowels.contains(oneWorg.getCharAt(i))) {
vowelCount++;
}
}
}
The above walks through each word; to then count the vowels. After the inner loop has finished, you know the vowels in the current word.
For the final solution, you would need:
String theWordWithTheMostVowelsSoFar = "";
int maxVowelCountSoFar = 0;
Simply check/update those two variables when the inner loop has finished. I leave that as exercise to the reader to not give all the things away.
回答2:
At the very least, you're missing the last word of the sentence since it isn't followed with a ' ' (try, e.g., to run this method with the input of "o oo" - you'll get the wrong output).
I'd go at this in another way though - I'd split the sentence to words, stream it, and take the max by number of vowels:
private static String getWordMostVowel(String sentence) {
return Arrays.stream(sentence.toLowerCase().split("\\s"))
.max(Comparator.comparing
(s -> s.chars()
.mapToObj(c -> Character.valueOf((char) c))
.filter(VOWELS::contains)
.count()))
.orElse(null);
}
回答3:
If indeed part of your exercise is to manually build your words from iterated characters (which is most likely the case since you haven't touched on Arrays yet) then there are a few things to consider all of which others here have already informed you about.
For the most part there are only a few things you really need to do so as to make your current code work as desired. In general it's mostly correct you just need to tweak it a little.
First off, don't destroy the originality of your sentence string by converting it all to lower letter case for the simple reason of comparing characters within a conditional statement as you do when placing the code line:
sentence = sentence.toLowerCase();
Understandably any word that is in a sentence can start with a upper case letter, be all upper case, or even camel-case but regardless you need that originality when creating and storing the actual word (the one with the most vowels in it) as it was originally supplied within the sentence. Of course to save you a lot of || (OR) statements you definitely want to work in a all lower or upper letter case but do it just before your IF conditional statement utilizing the Character.toLowerCase() method. Yes this takes a wee bit more time to process but it's negligible, for example:
word+= ch; // This is the same as: word = word + ch;
// ch is now only going to be used within the conditional
// statement below so we can modify it here.
ch = Character.toLowerCase(ch);
if ( ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ){
vowelCount++;
}
By doing it this way the character held in the variable ch can maintain its originality and when the word is created within the FOR loop (the one that will be held in the string variable word) it will be the very same as it was supplied within the sentence string.
Secondly, as already mentioned by others, the way your IF/ELSE is structured within the FOR loop, it does not properly take into account the last word of your supplied sentence string. The loop processes it but because there is no space character at the end of the sentence string the IF/ELSE can not do anything with the data to check it. There is a simple fix for this and that is to add a additional condition to go along with the (ch != ' ') condition so as to allow the IF/ELSE code within this condition block to continue processing that last characters of the sentence string. You can simply check to make sure the variable i used in the FOR loop has not reached it's limit therefore allowing the ELSE portion to process. Here's the fix:
// Can you see the added condition below?
if (ch != ' ' && i != (sentence.length() - 1)){
word+= ch; // This is the same as: word = word + ch;
// ch is now only going to be used within the conditional
// statement below so we can modify it here.
ch = Character.toLowerCase(ch);
if ( ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ){
vowelCount++;
}
}
else {
if(vowelCount > temp){
temp = vowelCount;
wordMostVowel = word;
}
word = ""; vowelCount = 0;
}
Thirdly, and again as mentioned by others, you need to zero out the vowelCount variable after every word so as to acquire the proper count. As a matter of fact, you need to properly clear the word string variable as well and give it a Null String ("") instead of a Space character (' '). If you don't then every word after the first word created will start with a Space character. You can actually see this done in the code example above within the ELSE code block.
Lastly, and this is just a suggestion, let the User know how many vowels were actually found when you display the word with the most vowels in it, perhaps like this:
System.out.println("The word with the most vowels (" + temp + ") is: " + " " + wordMostVowel);
You were darn close though...good job.
来源:https://stackoverflow.com/questions/40063011/word-with-the-most-vowels