簡體   English   中英

Java中搜索方法的nullpointer異常

[英]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()

請停止,你的代碼給我癌症! 您需要修復的代碼中存在許多樣式錯誤。

  • 首先在java中,方法名稱始終以小寫字母開頭 您使用Java編程,而不是使用C#編程,因此您需要使用Java命名約定。 這意味着您的方法應該稱為search ,而不是Search
  • 變量名稱也是如此。 無論如何, BF應該是什么意思? 請更換為in
  • 接下來,除非此方法位於自身表示該特定文件的對象中,否則全局變量f應作為參數傳遞。
  • BufferedReaderAutoCloseable ,因此您應該使用try-with-resources來處理關閉它。
  • 您需要向其添加一個javadoc注釋,使用@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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM