簡體   English   中英

我是一名新程序員,每次運行此代碼塊時,Java中都會出現一個空指針異常

[英]I'm a new programmer and every time I run this block of code I get a null pointer exception in Java

//This Is the Class
private String words;
private File textFile;
private Scanner inputFile;
StringBuilder stringBuilder = new StringBuilder();
public Scramble(String j) throws FileNotFoundException
{
File textFile = new File(j);

Scanner inputFile = new Scanner(textFile);
}

public String getRealWord() throws IOException                                    
{
//Make the loop while !null
//if null close the document
while (inputFile.hasNext())
    {

    stringBuilder.append(inputFile);

    }
    inputFile.close();



return stringBuilder.toString();
}

這是在主方法中對類的調用。String word = theScramble.getRealWord(); 我應該更改哪一部分以避免空指針異常

您將在本地范圍內重新聲明變量。 在您的Scramble構造函數中:

File textFile = new File(j);

...正在聲明一個名為textFile變量,該變量隱藏了也稱為textFile的實例成員。

您將需要更改:

public Scramble(String j) throws FileNotFoundException
{
   File textFile = new File(j);
   Scanner inputFile = new Scanner(textFile);
}

至:

public Scramble(String j) throws FileNotFoundException
{
   textFile = new File(j);
   inputFile = new Scanner(textFile);
}

這樣,您引用的是實例變量,而不是局部變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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