-3
錯誤與writeToFile()方法有關。我可以對它進行註釋並且它可以在沒有Exception錯誤的情況下運行。所以基本上,我試圖讓這些營養成分在文本文件上打印出來。 錯誤看起來像主 「顯示java.lang.NullPointerException在 Environment.writeToFile(Java1001.java:71)在 環境這個我不斷收到'線程異常'main「java.lang.NullPointerException'
「在線程異常」。(Java1001.java:54)在 Java1001 。主要(Java1001.java:43)」
import static java.lang.System.*;
import java.io.*;
public class Java1001
{
public static void main(String[] args) throws IOException
{
new Environment();
}
}
class Environment
{
private PrintStream outFile;
public Environment()
{
createOutputStream();
writeToFile();
}
public void createOutputStream()
{
// create outFile stream here
File outFile = null;
try
{
outFile = new File("Nutrition.txt");
outFile.createNewFile();
}
catch (Exception e){}
}
public void writeToFile()
{
outFile.println("NUTRITION FACTS");
outFile.println("======================================");
outFile.println("Serving Size 1 tbsp (6g)");
outFile.println("Servings Per Container about 4");
outFile.println("======================================");
outFile.println("Amount Per Serving");
outFile.println("Calories 20");
outFile.println("Calories from Fat 5");
outFile.println("======================================");
outFile.println("Total Fat 0.5g");
outFile.println("Sodium 280mg");
outFile.println("Total Carbohydrate 4g");
outFile.println("Sugars 0g");
outFile.println("Protein less than 1 g");
outFile.println("======================================");
}
}
您有2個名爲'outFile'的變量。 –
您正在初始化createOutputStream()中的局部變量'outFile'而不是數據成員,因此數據成員在'writeToFile()'中爲'null' – breezee