如何在arraylist中保存相同的对象而不覆盖第一行

时间:2016-09-04 01:48:44

标签: java arraylist java-io

我想要做的是将新的Transaction对象添加到事务Arraylist并保存到本地文件。然后将该数据拉回并迭代以填充transcationTotal。现在,当我保存新事务时,它会覆盖arraylist中的第一个对象,而不是将对象保存到下一行。

希望能够明白感谢你的帮助!

  //Enter Daily Transactions
    public void enterTransactions() {
        ArrayList<Transaction> transactions = new ArrayList();

        System.out.print("Please enter the transaction amount: $");
        Scanner amount = new Scanner(System.in);
        double transAmount = amount.nextDouble();
        System.out.print("Please enter name for this transaction: ");
        Scanner name = new Scanner(System.in);
        String transName = name.nextLine();
        System.out.println("What week is this transaction going under?: ");
        Scanner week = new Scanner(System.in);
        int transWeek = week.nextInt();
        Transaction transaction = new Transaction(transName,transAmount,transWeek);

        transactions.add(transaction);

        Iterator<Transaction> iterator = transactions.iterator();
        while (iterator.hasNext()) {

            Transaction i = iterator.next();
            i.printStats();
            int weekStat = i.getWeek();
            if (weekStat == 1) {
                double tAmount = i.getAmount();
                transactionTotalWeekOne = transactionTotalWeekOne - transAmount;
            } else if (weekStat == 2) {
                double tAmount = i.getAmount();
                transactionTotalWeekTwo = transactionTotalWeekTwo - transAmount;
            }

        }
        try {  // Catch errors in I/O if necessary.
// Open a file to write to, named SavedObj.sav.
            FileOutputStream saveFile = new FileOutputStream("C:/temp/transactions_log.sav");

// Create an ObjectOutputStream to put objects into save file.
            ObjectOutputStream save = new ObjectOutputStream(saveFile);

// Now we do the save.
            save.writeObject(transactions);

// Close the file.
            save.close(); // This also closes saveFile.
        } catch (Exception exc) {
            exc.printStackTrace(); // If there was an error, print the info.
        }


    }

1 个答案:

答案 0 :(得分:1)

实际上没有覆盖事务对象。您的ArrayList总是有1个元素,因为每次调用enterTransactions()方法时都会重新创建它。有一些方法可以防止这种情况。

  1. transactions ArrayList移出方法并将其设为静态。

  2. transactions ArrayList作为参数提供给enterTransactions(ArrayList transactions)方法。

  3. 因此,不会一次又一次地重新创建列表。

    P.S。每次需要输入时都不需要创建扫描仪。只需一台扫描仪即可。

相关问题