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.
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: