2011-09-07 89 views
1

我试图建立一个搜索按钮。点击搜索按钮后,它将从JComponent outTextArea中读入文本。扫描,字符串和文本区域的IProblems

它会读取每个单词,并将每个读入单词与我正在搜索的单词进行比较。我的问题是,它的工作原理很简单。它只读取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(); 


    } 

如果我添加休息;否则,它会搜索第一个单词。所以它告诉我,我的逻辑必须有所缺陷,而且不能这样做。

回答

1

你的问题是它会为所有单词设置标签的文字,但会这么快,以至于你没有时间阅读它。如果你想慢慢做,你需要使用一些东西来减慢循环,比如Swing Timer。也没有必要

if (suchAndSuch == true) 

清洁,以简单地做

if (suchAndSuch) 

例如:

if (e.getActionCommand().equals("Search")) { 
    final String strSearchString = searchTextField.getText(); 
    System.out.println(strSearchString); 
    String text = outTextArea.getText(); 
    System.out.println(text); 
    final Scanner sc = new Scanner(text); 
    int timerDelay = 2 * 1000; 

    new Timer(timerDelay, new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      if (sc.hasNext()) { 
       String s = sc.next(); 
       if (s.equals(strSearchString)) { 
       searchOutLabel.setText("Yes"); 
       } else { 
       searchOutLabel.setText("Non!"); 
       } 
      } else { 
       ((Timer)e.getSource()).stop(); 
       sc.close(); 
      } 
     } 
    }).start(); 
    } 

编辑1

如果你想打印是如果任何比赛都有被发现,那么你需要改变你的逻辑来设置文本字段找到任何匹配,然后退出该方法。如果没有找到匹配(你已经达到了while循环的结束),然后设置有标签:

 while (sc.hasNext()) { 
     String s = sc.next(); 
     if (s.equals(strSearchString)) { 
      searchOutLabel.setText("Yes"); 
      sc.close(); 
      return; 
     } 
    } 
    searchOutLabel.setText("Non!");   
    sc.close(); 
+0

不,这不是我想到的。我希望它检查从TextArea扫描的整个文本。我只想知道在另一个TextField中输入的搜索词是否在扫描文本中。如果是,“是”,那不是“否”。 –

+0

啊,那么你的逻辑是关闭的,因为它只会检查每个单词,并会很快完成。一旦遇到错误,您必须退出循环,这很简单。 –

+0

@NoCanDo:请参阅编辑 –

2
String s = sc.next(); //Change to 
String s = sc.nextLine(); 

同样改变

sc.hasNext(); to 
sc.hasNextLine(); 

而且在if true添加break statement声明。像这样

if (s.equals(strSearchString) == true) 
{ 
    searchOutLabel.setText("Yes"); 
    break; 
} 

else 
{ 

然后我必须评论你的格式偏好。让我开心并写上面这样

if (s.equals(strSearchString)) { 
    searchOutLabel.setText("Yes"); 
    break; 
} else { 
+0

好答案:1+ –