如何暂时挂起while循环
我正在编写拼写检查程序,它检查某个 .txt 文件的每个单词。它会在到达文件末尾时读取文件,当它发现不正确的单词时,它会在 JList 中建议正确的变体。用户选择一个并按“下一步”按钮。然后它继续阅读并搜索不正确的单词。
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
}
}
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
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
“暂停” while 循环不是正确的方法。相反,您的拼写检查算法应该参数化,以便您可以指定从哪里开始(与
indexOf
提供重载以允许您指定搜索应该开始的位置相同)。然后,如果您当前有注释
暂停循环直到按下“下一步”按钮
,您应该简单地退出该方法。然后,下次按下“下一步”按钮时,您将再次启动检查器,将您上次离开的文件中的位置传递到该方法中。 (或者,您可以将该位置存储在您班级的字段中。)"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.)我认为做这样的事情最简单的方法是以连续传递的方式编写循环代码(有选择性地,因为 Java 不支持真正的尾部调用)。本质上,您将一个函数(或 Java 中的 Runnable)传递给提示用户进行选择的代码,一旦用户做出选择,就执行该函数/runnable。当您在事件线程和工作线程之间来回切换时,这非常有效。
对此进行编码的一种简单方法是使用柯克的建议,即通过起始位置对函数进行参数化。
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.