2015-09-27 90 views
1

我一直在學習和堆疊一個問題。我嘗試從文本文件中搜索特定的名稱和員工編號。 我試圖在網上搜索一下,但是我沒有找到特別的結果。從文本文件中搜索特定文本

我該如何解決這個「無法找到符號」問題並正確地工作? 我得到錯誤,說,

.\txtFileReader.java:15: error: cannot find symbol while((line = filescan.readLine()) != null) ^ symbol: method readLine() location: variable filescan of type Scanner 1 error

我的代碼,

import java.util.*; 
import java.io.*; 

public class txtFileReader 
{ 
    private String words; 
    private Scanner typescan, filescan; 

    public void run() throws IOException 
    { 
     filescan = new BufferedReader(new FileReader("EmpInfo.txt")); 
     String line = ""; 
     words = typescan.nextLine(); 
     while((line = filescan.readLine()) != null) 
     { 
      if(line.matches(words)) 
      { 
       System.out.print(line); 
       break; 
      } 
      else 
      { 
       System.out.print("Sorry, could not find it."); 
       break; 
      } 
     } 
    } 
} 

更新:

我加的,而不是使用 「的BufferedReader filescan」 部分 「filescan」 不過當編譯後收到「NullPointerException」的另一個錯誤

Exception in thread "main" java.lang.NullPointerException 
     at txtFileReader.run(txtFileReader.java:15) 
     at Main.main(Main.java:9) 

......

Public void run() throws IOException 
     { 
     BufferedReader filescan = new BufferedReader(new FileReader("EmpInfo.txt")); 
     String line = ""; 
     words = typescan.nextLine(); 

...

UPDATE2:

它仍顯示空指針異常問題。

Exception in thread "main" java.lang.NullPointerException 
     at txtFileReader.run(txtFileReader.java:15) 
     at Main.main(Main.java:9) 

我不確定,但我假設因爲文本文件有問題要閱讀,它會給出NullPointerException?

回答

1

變化filescanBufferedReader

BufferedReader filescan; 

更新:

NullPointerException被拋出,因爲typescan未初始化。

String words = "Something"; 
Scanner typescan; // Not used 
BufferedReader filescan; 

filescan = new BufferedReader(new FileReader("EmpInfo.txt")); 
String line = ""; 
//words = typescan.nextLine(); // NullPointerException otherwise 
while((line = filescan.readLine()) != null) { 
    //if(line.matches(words)) { // What is this? 
    if(line.equals(words)) { 
     System.out.print(line); 
     break; 
    } else { 
     System.out.print("Sorry, could not find it."); 
      break; 
     } 
    } 
}