//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(); 我应该更改哪个部分以避免空指针异常
答案 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);
}
这样,您可以引用实例变量,而不是局部变量。