2016-09-26 33 views
0

我正在尝试编写一个程序,该程序将读取一个文件,并在具有最多连续元音的文件中查找该单词。我通过从文件中获取每个新单词,将其转化为charArray,然后评估数组中的字符以查看它们是否是元音来做到这一点。计数器保持连续元音的数量,然后如果当前字的计数器大于最大的前一个计数器值,则变量maxVowelString被设置为当前计数器的值。连续元音计数在无限循环中结束

我已经解决了一些错误与我如何处理charArray,但是当我在终端中运行它,它什么都不做,只是在一个无限循环中结束。我无法弄清楚是什么原因造成的。有没有人有任何想法? (我在编码方面有点新,所以可能会出现逻辑错误或者我不明白的地方)。

更新:我提出了几个建议的更改,并进行了调试。该程序陷入这个特定的循环,但我不明白为什么。

while ((i + n) < lowercase.length())  
       { 
        System.out.println("i + n " + (i + n)); 
        if ((charsList.get(i+n) == 'a') || (charsList.get(i+n) == 'e') || (charsList.get(i+n) == 'i') || (charsList.get(i+n) == 'o') || (charsList.get(i+n) == 'u')) 
        { 
         isVowel = true; 
         counter++; 
         System.out.println("counter " + counter); 
         i++; 
        } 
        else 
        { 
         isVowel = false; 
        } 
       } 
+3

'while(isVowel = true)'将始终为true,因为您正在将值赋给isVowel。如果你想比较需要'==',但是它几乎是一个无限循环,因为你从不将它设置为false。 – scrappedcola

+0

我刚刚意识到这两个,并修复它们(只是更新它),但它仍然无法正常工作。 –

+1

提炼逻辑,只是检查字符,如果它是一个元音继续,否则走出循环,最后比较当前计数与最大计数,如果更大然后改变最大否则继续,下一个字 –

回答

0

您在第二个while循环中存在缺陷,您正在迭代单词。设置n = 1和计数器= 0会在找到下一个字母为元音时导致无限循环。它在同一个字母上无限地迭代。下面是更新的代码段(仅逻辑更新):

while (fileIn.hasNext()) 
{ 
    word = fileIn.next(); 
    String lowercase = word.toLowerCase(); 
     char[] wordChar = word.toCharArray(); 
     int i = 0; 
     int counter = 0; 
     while (i < lowercase.length()) { 
      if ((wordChar[i] == 'a') || (wordChar[i] == 'e') || (wordChar[i] == 'i') || (wordChar[i] == 'o') 
        || (wordChar[i] == 'u')) { 
       counter++; 
      } else { 
       i++; 
       continue; 
      } 
      i++; 

     } 
     if (counter > maxVowelString) { 
      maxVowelString = counter; 
      maxVowelWord = lowercase; 
     } 
} 
    System.out.println("The word in this file with the most consecutive vowels is " + maxVowelWord + "."); 
    System.out.println("It has " + maxVowelString + "vowels."); 
0

首先,如果(fileIn.hasNext())是符合而wrong.Replace它(fileIn.hasNext())。这是因为当你从文件中读取时你不知道它什么时候结束,所以这个while循环将检查你的文件是否有下一个单词..注 - 当你调用hasNext()从文件读取,否则你将永远有一个无限循环这只是一个通用信息,因为您正在阅读文件(word = fileIn.next()),因此没有问题)。

其次,看这同时LOOP-

while (isVowel == true) { counter = 0; int n = 1; if ((wordChar[i+n] == 'a') || (wordChar[i+n] == 'e') || wordChar[i+n] == 'i') || (wordChar[i+n] == 'o') || (wordChar[i+n] == 'u')) { isVowel = true; counter++; } else isVowel = false; n++; }

现在假设 “排队” 一词-the第一,如果条件为真,当n = 1;然后反++;循环再次运行和现在为n = 2如果条件满足等等,直到遇到'i'的最后一个元音。现在,相应地我的值是什么(只是看到它)....所以,要使它正确,这必须是下面的循环...

`while (isVowel == true) 
     { 
      counter = 0; 
      int n = 1; 
      if ((wordChar[i+n] == 'a') || (wordChar[i+n] == 'e') || wordChar[i+n] == 'i') || (wordChar[i+n] == 'o') || (wordChar[i+n] == 'u')) 
      { 
       isVowel = true; 
       counter++;i++; 
      } 
      else{ 
       isVowel = false; 
       i++;continue; 
      } 
      n++; 
     }` 

正如你想从位置开始到你有的位置检查..

希望这可能会帮助你。