gpt4 book ai didi

java - 在java中打印元音数量最多的单词

转载 作者:行者123 更新时间:2023-11-30 01:46:33 25 4
gpt4 key购买 nike

我想打印包含最大元音数的单词。但问题是包含最大数量的句子的最后一个单词没有打印。请帮我解决这个问题。我的代码如下。当我输入 'Happy New Year' 时,输出是 'Yea' 。但我希望输出是 'Year'

import java.util.Scanner;
public class Abcd {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter The Word : ");
String sentence = sc.nextLine();
String word = "";
String wordMostVowel = "";
int temp = 0;
int vowelCount = 0;
char ch;
for (int i = 0; i < sentence.length(); i++) {
ch = sentence.charAt(i);
if (ch != ' ' && i != (sentence.length() - 1)) {
word += ch;
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;
}
}
System.out.println("The word with the most vowels (" + temp + ") is: " + " " + wordMostVowel);
}
}

最佳答案

您在空格处剪切单词(正确),但您也在最后一个字符处剪切,即使它不是空格(因此永远不会处理该字符)。这是不正确的。

这是一种可能性:

import java.util.Scanner;

public class Abcd {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the sentence : ");
String sentence = sc.nextLine();
String wordMostVowels = "";
int maxVowelCount = 0;

for (String word : sentence.split(" ")) {
int vowelCount = 0;
for (char c : word.toLowerCase().toCharArray()) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
vowelCount++;
}
}

if (vowelCount > maxVowelCount) {
maxVowelCount = vowelCount;
wordMostVowels = word;
}
}

System.out.println("The word with the most vowels (" + maxVowelCount + ") is: " + wordMostVowels);
}
}

关于java - 在java中打印元音数量最多的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57735526/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com