[英]nullpointer exception at a search method in Java
所以我追蹤了這個bugger,但我並沒有更接近理解錯誤。 這是編譯器說的:
在TestFile.main的BasicFile.Search(BasicFile.java:215)中的線程“main”java.lang.NullPointerException中的異常(TestFile.java:42)
第215行是以while開頭的第一行。
String Search(String key) throws IOException {
int lines = 0;
String line = "";
String foundAt = "";
BufferedReader BF = new BufferedReader(new FileReader(f));
try {
while ((line = BF.readLine().toLowerCase()) != null) {
lines++;
//create tokenizer words with what is in line
StringTokenizer words = new StringTokenizer(line);
while(words.hasMoreTokens()) { //while words has tokens left
//go to next token and compare to key
if (words.nextToken().equals(key.toLowerCase()))
foundAt = foundAt + "\n" + lines + ":" + line;
//do nothing continue loop
}
}
BF.close();
} catch(FileNotFoundException e) {
}
return foundAt;
}
當緩沖區讀取器用完行時,它返回null
。 您試圖在null上調用toLowerCase
方法,最終拋出空指針異常。
在確保行非空之前,不要求您執行toLowerCase
的方式重構代碼。
例如:
String next;
while ((next = BF.readLine()) != null) {
String line = next.toLowerCase();
// ...
}
while ((line = BF.readLine().toLowerCase()) != null)
如果BF.readline()返回null會發生什么?
從測試中刪除.toLowerCase()
請停止,你的代碼給我癌症! 您需要修復的代碼中存在許多樣式錯誤。
search
,而不是Search
。 BF
應該是什么意思? 請更換為in
。 f
應作為參數傳遞。 BufferedReader
是AutoCloseable
,因此您應該使用try-with-resources來處理關閉它。 @param
記錄其參數,使用@return
它的參數,以及它可能需要使用@exception
IOException
。 以下是代碼的大部分修復版本:
/**
* Needs Javadoc
*/
String search(String key, File f) throws IOException {
int lines = 0
String line = "";
String foundAt = "";
try(BufferedReader in = new BufferedReader(new FileReader(f)) {
while ((line = in.readLine().toLowerCase()) != null) { //the line in question
lines++;
StringTokenizer words = new StringTokenizer(line);
while(words.hasMoreTokens())
if (words.nextToken().equals(key.toLowerCase()))
foundAt = foundAt + "\n" + lines + ":" + line;
}
} catch(FileNotFoundException e){}
return foundAt;
}
現在,這里的問題是in.readline()
有時返回null
。 在null
上調用方法始終是NullPointerException
。 因此,當您嘗試調用null
的缺少toLowerCase()
方法時,會出現NullPointerException
。
確保它為非null 后,您需要將其轉換為toLowerCase
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.