-1

所以我有这个代码:

package Firstpack;

import java.io.*;
import java.util.*;

public class Main {

    public static void menu() {
        System.out.println("Welcome");
        System.out.println("1. Add a record ");
        System.out.println("2. See all records ");
        System.out.println("3. See a category");
        System.out.println("4. Total spend(Year)");
        System.out.println("5. Spend in a month");
        System.out.println("6. Chose by index");
        System.out.println("7. Exit ");

        System.out.print(">");
        Scanner in = new Scanner(System.in);
        int enteredInt = in.nextInt();
        in.close();

        switch (enteredInt) {
        case 1:
            recording();
            break;
        case 2:
            System.out.print(" You have chosen -> See all records");
            break;
        case 3:
            System.out.print(" You have chosen -> See a category");
            break;
        case 4:
            System.out.print(" You have chosen -> Total spend(Year)");
            break;
        case 5:
            System.out.print(" You have chosen -> Spend in a month");
            break;
        case 6:
            System.out.print(" You have chosen -> Chose by index");
            break;
        case 7:
            System.out.print(" Bye! ");
            break;
        default:
            menu();
        }

    }

    public static void recording() {
        System.out.println(" You have chosen -> Add a record");

        record rec = new record();
        Scanner in = new Scanner(System.in);

        System.out.print("Enter Amount > ");
        rec.amount = in.nextDouble();
        System.out.print("Enter Category > ");
        rec.category = in.next();
        System.out.print("Enter Details > ");
        rec.details = in.next();

        try {
            FileWriter fw = new FileWriter("findme.txt");
            BufferedWriter bw = new BufferedWriter(fw);

            bw.write(String.valueOf(rec.amount));
            bw.write(rec.category);
            bw.write(rec.details);

            bw.close();
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        menu();
    }
}

它向我抛出了这个:

Exception in thread "main" java.lang.NullPointerException
    at java.io.Writer.write(Unknown Source)
    at Firstpack.Main.recording(Main.java:68)
    at Firstpack.Main.menu(Main.java:25)
    at Firstpack.Main.main(Main.java:82)

我不知道如何解决这个问题。这里有什么问题?

4

1 回答 1

1

问题是由于in.close()在您的菜单方法中调用。不仅in.close()关闭Scanner对象,而且它也恰好关闭System.in。当您输入 1 作为菜单选择时,您的recording()方法会被调用,该方法会创建一个Scanner尝试使用 now closed的新方法System.in

这是一篇解决类似问题的帖子: 尝试编写一个方法来检查 JAVA 中的用户输入,获取 NoSuchElementException

于 2012-09-13T18:22:57.043 回答