Java程序问题:如何获取句子中所有含最多元音的单词
问题分析与修复方案
首先咱们来拆解下你代码里的核心问题:当遇到元音数比当前最大值更多的单词时,你只重置了maxvowel和清空了maxWord,但没有把这个新的“最大元音单词”加入到结果里。比如输入red book friend时,book的元音数(2)比red的(1)大,这时候代码会清空maxWord但不把book加进去,后面处理friend时才会将其加入,最终结果就漏掉了book。另外初始时maxWord设为空字符串,第一个单词的逻辑处理也存在遗漏风险。
下面给出两种修复方案,你可以根据需求选择:
方案一:最小改动修复原逻辑
只调整maxVowelWords方法的逻辑,确保遇到更大元音数的单词时,不仅更新最大值,还要把当前单词加入结果;同时正确初始化maxWord,并从第二个单词开始遍历(避免重复处理第一个单词):
public class Methods6 { public static String getSentence() { Scanner scanner = new Scanner(System.in); System.out.print("cumleni daxil et:"); String sentence = scanner.nextLine(); return sentence; } public static int CountVowel(String words) { int count = 0; char[] vowel = {'a', 'e', 'i', 'o', 'u'}; for (int i = 0; i < words.length(); i++) { char ch = words.charAt(i); for (char cc : vowel) { if (ch == cc) { count++; } } } return count; } public static String maxVowelWords() { String sentence = getSentence().toLowerCase(); String[] words = sentence.split(" "); // 处理空输入的边界情况,避免数组越界 if (words.length == 0) { return ""; } int maxvowel = CountVowel(words[0]); String maxWord = words[0]; // 初始化为第一个单词 // 从第二个单词开始遍历 for (int i = 1; i < words.length; i++) { int count = CountVowel(words[i]); if (count > maxvowel) { maxvowel = count; maxWord = words[i]; // 重置结果为当前单词(新的最大值) } else if(count == maxvowel){ maxWord = maxWord + " " + words[i]; // 追加相同元音数的单词 } } return maxWord; } }
方案二:重构逻辑(更易读、更健壮)
把逻辑拆分成两步:先遍历所有单词找到最大元音数,再收集所有符合该数量的单词。这种方式用StringBuilder拼接结果,效率更高,逻辑也更清晰,不容易出错:
public class Methods6 { public static String getSentence() { Scanner scanner = new Scanner(System.in); System.out.print("cumleni daxil et:"); String sentence = scanner.nextLine(); return sentence; } public static int CountVowel(String words) { int count = 0; char[] vowel = {'a', 'e', 'i', 'o', 'u'}; for (char ch : words.toCharArray()) { // 简化遍历方式 for (char cc : vowel) { if (ch == cc) { count++; break; // 找到元音后直接跳出内层循环,优化性能 } } } return count; } public static String maxVowelWords() { String sentence = getSentence().toLowerCase(); String[] words = sentence.split(" "); if (words.length == 0) { return ""; } // 第一步:计算所有单词的元音数,找到最大值 int maxVowelCount = 0; int[] vowelCounts = new int[words.length]; for (int i = 0; i < words.length; i++) { vowelCounts[i] = CountVowel(words[i]); if (vowelCounts[i] > maxVowelCount) { maxVowelCount = vowelCounts[i]; } } // 第二步:收集所有元音数等于最大值的单词 StringBuilder maxWords = new StringBuilder(); for (int i = 0; i < words.length; i++) { if (vowelCounts[i] == maxVowelCount) { if (maxWords.length() > 0) { maxWords.append(" "); } maxWords.append(words[i]); } } return maxWords.toString(); } }
两种方案都能解决你的问题:输入red book friend时会返回book friend,输入book red friend时也会返回book friend,完全符合预期。
测试类无需修改,保持原样即可:
public class Test { public static void main(String[] args) { System.out.println(Methods6.maxVowelWords()); } }
内容的提问来源于stack exchange,提问作者Ulviyya Ibrahimli
相关产品推荐
相关产品推荐

