开发者

how to temporarily suspend while loop

I'm writing spell checker program, which checks every word of some .txt file. it reads file while开发者_如何转开发 end of file is reached, and when it finds incorrect word it suggests correct variants in JList. and user chooses one and presses "next" button. Then it continues reading and searching for incorrect word.

while(EOF is not reached)
{
    check(word);//this returns array of suggestions

    if("next" button is pressed)
    {
        list.getSelectedWord() and continue while loop
    } else {
        suspend loop until "next" button is pressed
    }
}


"Suspending" the while loop is not the right approach. Instead, your spell checking algorithm should be parameterized so that you can specify where to begin (in the same way that indexOf offers an overload that allows you to specify where the search should start).

Then, where you currently have the comment suspend loop until "next" button is pressed, you should simply exit out of the method. Then, the next time the "next" button is pressed, you start up the checker again, passing into that method the position in the file you had left off. (Alternatively, you could store that position in a field of your class.)


I think that the easiest way to do something like this is to code the loop in continuation passing style (selectively since Java doesn't support real tail calls). Essentially you pass a function (or Runnable in Java) to the code that prompts the user for his choice and once the user makes his choice, execute the function/runnable. This works well when you're bouncing back and forth between the event thread and worker threads.

An easy way to code this is using Kirk's suggestion of parameterizing the function by the starting position.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜