2011-09-07 84 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+ –