0

テキストをファイルに書き込むアプリケーションがあります。ファイルが存在しない場合は、作成されます。

アプリケーションを初めて実行すると、すべてが正しく機能し、ファイルが作成されます。ただし、その後は毎回、アプリケーションがクラッシュします。何度も機能しない理由を説明してください。

私のコードは次のとおりです...

public class Apples {

    Formatter x;
    File file = new File("myfile.txt");

    public Apples() {

        if (!file.exists()) {
            try {
                x = new Formatter("myfile.txt");
            }
            catch (Exception e) {
                System.out.println("There was an error creating the file");
            }

            System.out.println("The file was created");
        } 
        else {
            System.out.println("The file already exists");
            }

        x.format("%s", "text");
        x.close();
    }

    public static void main(String[] args) throws FileNotFoundException {
        Apples a = new Apples();
    }

}
4

2 に答える 2

4

ファイルが既に存在する場合に値を割り当てていないためNullPointerException、問題が発生していると思われます。x.format("%s", "text");x

于 2012-04-07T04:16:52.147 に答える
0

2 回目xは初期化しないため null です。

于 2012-04-07T04:21:02.080 に答える