[英](Processing) I get a null pointer exception when i try to run this code
[英]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.