2011-08-21 81 views
1

我想驗證我的文本文件是否已經包含用戶在文本字段中輸入的單詞。當用戶點擊驗證,如果單詞已經在文件中,用戶將輸入另一個單詞。如果單詞不在文件中,則會添加單詞。我的文件的每一行都包含一個單詞。我把System.out.println看到正在打印什麼,它總是說這個詞不存在於文件中,但它不是真的......你能告訴我什麼是錯的嗎?(JAVA)比較用戶輸入的單詞與文本文件中包含的另一個單詞

謝謝。

class ActionCF implements ActionListener 
    { 

     public void actionPerformed(ActionEvent e) 
     { 

      str = v[0].getText(); 
      BufferedWriter out; 
      BufferedReader in; 
      String line; 
      try 
      { 

       out = new BufferedWriter(new FileWriter("D:/File.txt",true)); 
       in = new BufferedReader(new FileReader("D:/File.txt")); 

       while ((line = in.readLine()) != null) 
       { 
        if ((in.readLine()).contentEquals(str)) 
        { 
         System.out.println("Yes"); 

        } 
        else { 
         System.out.println("No"); 

         out.newLine(); 

         out.write(str); 

         out.close(); 

        } 

       } 
      } 
      catch(IOException t) 
      { 
       System.out.println("There was a problem:" + t); 

      } 
     } 

    } 
+0

哪些內容Ø f您正在使用的文件,您的輸入是什麼,控制檯吐出了什麼? –

+0

您是否嘗試過使用掃描儀?我總是比較喜歡掃描儀。 – buch11

+0

嗨尼古拉斯。每行文本文件包含1個字。用戶在textField中輸入一個單詞,並且我想知道這個單詞是否已經在文本文件中,如果沒有,請添加它。 – ARH

回答

6

它看起來像你打電話in.readLine()兩次,一次是在while循環並且再次在有條件的。這導致它跳過每隔一行。此外,您要使用String.contains而不是String.contentEquals,因爲您只是檢查行是否包含這個詞。此外,您希望等到整個文件已被搜索,然後再決定找不到該單詞。所以,試試這個:

//try to find the word 
BufferedReader in = new BufferedReader(new FileReader("D:/File.txt")); 
boolean found = false; 
while ((line = in.readLine()) != null) 
{ 
    if (line.contains(str)) 
    { 
     found = true; 
     break; //break out of loop now 
    } 
} 
in.close(); 

//if word was found: 
if (found) 
{ 
    System.out.println("Yes"); 
} 
//otherwise: 
else 
{ 
    System.out.println("No"); 

    //wait until it's necessary to use an output stream 
    BufferedWriter out = new BufferedWriter(new FileWriter("D:/File.txt",true)); 
    out.newLine(); 
    out.write(str); 
    out.close(); 
} 

(從我的例子中省略異常處理)

編輯:我只是重新閱讀您的問題 - 如果每行只包含一個字,然後equalsequalsIgnoreCase會工作,而不是的contains,確保呼籲linetrim測試之前,過濾掉任何空白:

if (line.trim().equalsIgnoreCase(str)) 
... 
+1

另一件值得指出的事情是,如果文件包含兩行不是輸入的單詞,第一行將關閉「BufferedWriter」,第二行將拋出異常(導致while循環終止),如它會試圖寫入一個關閉的'BufferedWriter'。 –

+0

@nicholas - 是的,編輯我的答案來涵蓋這個問題。 –

+0

非常感謝您的幫助! :-) – ARH

相關問題