kellykels21 kellykels21 - 2 months ago 6
Java Question

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

What I would like to do is add new Transaction objects to the transactions Arraylist and save to a local file. Then pull that data back in and iterate over to populate a transcationTotal. Right now when i save a new transaction it overwrites the first object in the arraylist instead of saving the object to the next line.

Hope that was clear enough to understand thanks for your help!

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


}

Answer

Actually there is no overwriting on transaction objects. Your ArrayList always will have 1 element because you are recreating it every time enterTransactions() method called. There are some ways to prevent that.

  1. Move your transactions ArrayList out of the method and make it static.

  2. Give the transactions ArrayList to your enterTransactions(ArrayList transactions) method as a parameter.

Thus the list will not be recreated again and again.

P.S. You do not need to create a Scanner every time you need an input. Just one scanner is enough in your case.

Comments