gpt4 book ai didi

java - 为什么这不排除元音?

转载 作者:行者123 更新时间:2023-12-01 23:29:39 27 4
gpt4 key购买 nike

这来 self 们老师给我们的单词库,我应该返回最长的没有元音的单词。但它要么返回一个带有元音的单词,要么什么也不返回。请帮忙。

//最长的没有元音的单词是什么(y也算元音)?

   public static void Question7()
{
// return the number of words in wordlist ending in "ing"
String longestWordSoFar = " ";
System.out.println("Question 7:");
int numberOfWords = 0; //count of words ending in ing
for(int i = 1; i < WordList.numWords(); i++) // check every word in wordlist
{
if(noVowel(WordList.word(i))) { // if the length is greater than the previous word, replace it
{

if(WordList.word(i).length() > longestWordSoFar.length())
longestWordSoFar=WordList.word(i);
}
}

}
System.out.println("longest word without a vowel: " + longestWordSoFar);
System.out.println();
return;
}
public static boolean noVowel(String word) {
//tells whether word ends in "ing"
for(int i = 0; i < word.length(); i++) {
//doesnt have a vowel - return true
if (word.charAt(i) != 'a') {
return true;
}
if (word.charAt(i) != 'e') {
return true;
}
if (word.charAt(i) != 'i') {
return true;
}
if (word.charAt(i) != 'o') {
return true;
}
if (word.charAt(i) != 'u') {
return true;
}
if (word.charAt(i) != 'y') {
return true;
}

}
return false;
}

最佳答案

在您的方法 noVowel 中,一旦找到不是 ae 的字符,您就会返回 true code>、iouy。这是错误的。您宁愿在找到这些字符之一后立即返回 false,而仅在单词中没有这些字符时才返回 true

像这样:

 public static boolean noVowel(String word) {
for(int i = 0; i < word.length(); i++) {
//if a vowel found then return false
if (word.charAt(i) == 'a') {
return false;
}
if (word.charAt(i) == 'e') {
return false;
}
if (word.charAt(i) == 'i') {
return false;
}
if (word.charAt(i) == 'o') {
return false;
}
if (word.charAt(i) == 'u') {
return false;
}
if (word.charAt(i) == 'y') {
return false;
}

}
return true; // No vowel found, return true
}

关于java - 为什么这不排除元音?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19535462/

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