use*_*612 1 java string for-loop
我需要在用户输入的字符串中找到所有元音,然后在屏幕上打印出元音最多的单词.
该程序使用用户输入.
用户以小写字母键入字符串.
例如
"我喜欢java编程"
它应该读出来:
程序设计
我尝试将字符串拆分成不同的单词,这是有效的.
我只是不知道如何应用"for"循环来搜索不同的单词.我需要在方法中工作,所以这是我用来在字符串中找到元音的方法:
public void findvowel(){
for(int index = 0;index < word.length();index++){
char vowel = word.charAt(index);
if( (vowel == 'a')||
(vowel == 'e')||
(vowel == 'i')||
(vowel == 'o')||
(vowel == 'u')){
System.out.println(vowel);
}
}
}
Run Code Online (Sandbox Code Playgroud)
但我知道这不起作用.你能帮助我吗?
public class MaxVowels {
public static void main(String[] args) {
String sentence = "This is a loooooooooong sentence";
int maxVowelCount = 0;
String wordsWithMostVowels = null;
String[] words = sentence.split(" ");
for(String word : words){
int vowelCount = 0;
word = word.toLowerCase();
for(int i = 0; i < word.length() ; i++){
char x = word.charAt(i);
if(x == 'a' || x == 'e' || x == 'i' ||
x == 'o' || x == 'u'){
vowelCount++;
}
}
if(vowelCount > maxVowelCount){
maxVowelCount = vowelCount;
wordsWithMostVowels = word;
}
}
System.out.println("Word with most vowels is: " + wordsWithMostVowels);
}
}
Run Code Online (Sandbox Code Playgroud)
代码相当简单,无需解释=)
代码忽略了两个单词具有相同元音数的情况.在这种情况下,第一个单词将用作具有大多数元音的单词.