如何在不覆盖第一行的情况下将相同的对象保存在数组列表中

How to save the same object in an arraylist without overwriting the first line

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

希望您已经清楚地理解了,感谢您的帮助!

  //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.
        }


    }

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

  1. 将您的 transactions ArrayList 移出方法并使其成为静态的。

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

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

P.S。您不需要在每次需要输入时都创建扫描仪。对于您的情况,只需一台扫描仪就足够了。