我是一个新的程序员,每次运行这段代码时,我都会在Java中得到一个空指针异常

时间:2014-07-24 02:10:51

标签: java nullpointerexception

//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();
}

这是main方法中对类的调用     String word = theScramble.getRealWord(); 我应该更改哪个部分以避免空指针异常

1 个答案:

答案 0 :(得分:3)

您在本地范围内重新声明变量。在Scramble构造函数中:

File textFile = new File(j);

...声明一个名为textFile new 变量,该变量隐藏了也称为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);
}

这样,您可以引用实例变量,而不是局部变量。