0

这是从老师给我们的单词库中提取的,我应该返回没有元音的最长单词。但它要么返回一个带有元音的单词,要么什么都不返回。请帮忙。

//没有元音的最长单词是什么(将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;
        }
4

2 回答 2

3

在您的方法中,一旦找到不是, , , , , 或的字符,noVowel您就会返回。这是错误的。您宁愿在找到其中一个字符后立即返回,并且仅在单词中没有这些字符时才返回。trueaeiouyfalsetrue

像这样:

 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
}
于 2013-10-23T07:31:39.987 回答
0

更改您的 noVowel 方法,例如:

public static boolean noVowel(String word) {
   boolean noVowel=true;
   for(int i=0;i<word.length();i++){
     char ch=word.charAt(i);
     if(ch=='a' ||ch=='e' ||ch=='i' ||ch=='o' ||ch=='u' ||ch=='y'){
       noVowel=false;
       break;
     }

   } 
    return noVowel;
}
于 2013-10-23T07:36:40.847 回答