虽然循环在它应该出现之前就已经破了,逻辑问题?

时间:2014-10-19 16:10:52

标签: java loops logic

在我写的程序中,我有一个单词列表,对于每个单词,这个方法应该贯穿整个字典并将给定的单词与字典进行比较。出于某种原因,它只比较第一个单词,但继续通过givenWordCounter递增而不通过字典运行它。

我的逻辑肯定有问题,但我不知道它是什么。下面是我提出的伪代码以及代码本身,你看到我犯的任何重大错误吗?

伪代码:

for each word in the givenWords list:
  while dictionaryCounter < dictionary.size():
    run word in givenWord list at givenWordCounter index through the dictionary
    increment thousandCounter by 1000
increment givenWordCounter by 1

program should loop through every word in givenWords list & for each givenWord 
loop through dictionary.prefix once. after dictionary.prefix loop is done move
on to next givenWord

和代码:

public static void runProgram(){
int givenWordCounter = 0; 
int thouCount = 1000;

while (givenWordCounter < givenWords.size()){
    while (thouCount < theDictionary.size()){

        Dictionary.prefix(givenWords.get(givenWordCounter), theDictionary, counter, thouCount);
        thouCount = thouCount + 1000;
    }
    givenWordCounter++;
 }
}

根据我对如何编写代码的理解它应该有效,但我猜错了,我猜错了?

修改 我被要求包含在Dictionary类中调用的代码,这里是(需要通过赋值递归):

 public static void prefix (String origWord, List<String> theDictionary, int beginFrom, int endAt){


            // if the words don't match recurse through this same method in order to move on to the next word
        if (beginFrom < theDictionary.size() && counter < endAt){   
          if ( origWord.charAt(0) != theDictionary.get(beginFrom).charAt(0) || origWord.length() != theDictionary.get(beginFrom).length()){

              counter = counter + 1;
              prefix(origWord, theDictionary, beginFrom+1, endAt);  
          }

          // if the words first letter and size match, send the word to prefixLetterChecker to check for the rest of the prefix.
          else{
              prefixLetterChecker(origWord, theDictionary.get(beginFrom), 1);
              counter = counter + 1;
              prefix(origWord, theDictionary, beginFrom+1, endAt);
          }
        }



     }

2 个答案:

答案 0 :(得分:3)

交换(并略微改变)这两行,

int thouCount = 1000;
while (givenWordCounter < givenWords.size()){

(我认为应该是)

while (givenWordCounter < givenWords.size()){
  int thouCount = 1000 + givenWordCounter; // <-- to offset givenWordCounter.

因为您需要在每次循环迭代时重置thouCount

答案 1 :(得分:0)

我其实只是想出来了!

问题在于“计数器”在字典大小的末尾,我需要做的就是在每次运行字典后添加一个让计数器回零的东西! D'哦。我应该删除这个问题吗?