扫描、字符串和文本区域的问题
我正在尝试构建一个搜索按钮。单击搜索按钮后,它将从 JComponent outTextArea 读取文本。
它将读取每个单词,并将每个读入的单词与我正在搜索的单词进行比较。我的问题是,它确实有效。它只读取 outTextArea 中的最后一个单词。
这是代码片段
if(e.getActionCommand().equals("Search"))
{
String strSearchString = searchTextField.getText();
System.out.println(strSearchString);
String text = outTextArea.getText();
System.out.println(text);
Scanner sc = new Scanner(text);
while(sc.hasNext() == true)
{
String s = sc.next();
if (s.equals(strSearchString) == true)
{
searchOutLabel.setText("Yes");
}
else
{
searchOutLabel.setText("Non!");
}
}
sc.close();
}
如果我添加break;之后,它将搜索第一个单词。所以它告诉我我的逻辑一定有缺陷,不能这样做。
I'm trying to build in a search button. Upon clicking the search button, it will read in the text from JComponent outTextArea.
It will read it each word, and compare each read-in word to the word I'm searching for. My problem is, it works, sorta. It only reads the last word from the outTextArea.
This is the code snippet
if(e.getActionCommand().equals("Search"))
{
String strSearchString = searchTextField.getText();
System.out.println(strSearchString);
String text = outTextArea.getText();
System.out.println(text);
Scanner sc = new Scanner(text);
while(sc.hasNext() == true)
{
String s = sc.next();
if (s.equals(strSearchString) == true)
{
searchOutLabel.setText("Yes");
}
else
{
searchOutLabel.setText("Non!");
}
}
sc.close();
}
If I add break; after else, it'll search the first word. So it tells me my logic must be flawed somewhat and it can't be done this way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
同样,更改
还在
if true
语句中添加一个break 语句
。像这样然后我必须评论你的格式偏好。让我开心,上面这样写
Similarly change
Also add a
break statement
in yourif true
statement. Like thisThen I must comment on your formating preferences. Make me happy and write the above like this
您的问题是,它将为所有单词设置标签的文本,但速度太快,以至于您没有时间阅读它。如果您想慢慢地进行,则需要使用一些东西来减慢循环速度,例如 Swing Timer。也不需要
Cleaner 简单地执行
例如:
编辑 1
如果您想在找到任何匹配项时打印 yes,那么您需要更改逻辑以设置文本字段(如果有任何匹配项)找到然后退出该方法。如果没有找到匹配项(您已到达 while 循环的末尾),则在那里设置标签:
Your problem is that it will set the text for the label for all words, but will do so so quickly that you won't have time to read it. If you want to do it slowly you'll need to use something to slow down the loop such as a Swing Timer. Also no need for
Cleaner to simply do
For example:
Edit 1
If you want to print yes if any match has been found, then you'll need to alter your logic to set the textfield if any match is found then exit the method. If no match is found (you've reached the end of the while loop), then set the label there: