在用户输入中获取LocalDateTime

时间:2019-04-07 20:10:18

标签: java

我正在研究一种方法,用户可以在其中插入交易明细。在该字段之一中,存在一个事务处理时间,该事务处理时间是使用java localdatetime自动设置的。但是,在运行程序时,它会给我这个错误:

Exception in thread "main" java.lang.NullPointerException: temporal
    at java.util.Objects.requireNonNull(Objects.java:228)
    at java.time.format.DateTimeFormatter.formatTo(DateTimeFormatter.java:1741)
    at java.time.format.DateTimeFormatter.format(DateTimeFormatter.java:1720)
    at project.TradeManager.saveToFile(TradeManager.java:59)
    at project.MainApp.addTrade(MainApp.java:649)
    at project.MainApp.main(MainApp.java:138)

MainApp

public static void addTrade() {     
        AnimalManager aMgr = new AnimalManager();
        aMgr.loadFromFile("AnimalDetails.txt");

        TradeManager tMgr = new TradeManager();
        tMgr.loadFromFile("TradeDetails.txt", aMgr);

        String tradeID = "TRD" + ++idCount;

        Scanner an = new Scanner(System.in); //Scanner for user input
        TradeRecord tr = new TradeRecord();

        //Insert trade informations       
        System.out.println("Trade ID (automatically set)");
        tr.setID(tradeID);

        System.out.println("Animal ID (Must be recorded already): ");
        tr.setAnimal(aMgr.getAnimalById(an.next()));

        System.out.println("Seller: ");
        tr.setSeller(an.next());

        System.out.println("Buyer: ");
        tr.setBuyer(an.next());

        System.out.println("Transaction Time (automatically set)");
        LocalDateTime.now();

        System.out.println("Way of trade: ");
        tr.setwayOfTransaction(an.next());

        boolean added = tMgr.addTrade(tr);

        if(added) {
            System.out.println("Added successfully.");
        }else {
            System.out.println("Duplicate. Fail");
        }

        //Save to file
        aMgr.saveToFile("AnimalDetails.txt");
        tMgr.saveToFile("TradeDetails.txt");
    }

TradeManager

public void saveToFile(String filename) {
 StringBuilder output = new StringBuilder();
 for (TradeRecord tr: tradeList) {
  output.append(tr.getID()).append(",").append(tr.getAnimal().getID()).append(",")
   .append(tr.getSeller()).append(",").append(tr.getBuyer())
   .append(",").append(DTF.format(tr.getTransactionTime())).append(tr.getwayOfTransaction()).append(",").append("\r\n");
 }
 try (FileWriter fw = new FileWriter(new File(filename))) {
  fw.write(output.toString());
 } catch (IOException e) {
  System.out.println("Trades cannot be saved: " + e);
 }
}

0 个答案:

没有答案