public class Lab2 { public static void main (String [] args) { File custFile = new File ("customer.dat"); File transFile = new File ("transaction.dat"); File oldCustFile = new File("oldcustomer.dat");
// Make sure the files exist if (checkForFileErrors (custFile, transFile)) return;
// Rename the customer file custFile.renameTo(oldCustFile);
// Open the files for reading Scanner custScanner = null; Scanner transScanner = null;
try { custScanner = new Scanner (oldCustFile); custScanner.useDelimiter("[:\r\n]+");
transScanner = new Scanner (transFile); transScanner.useDelimiter("[:\r\n]+"); } catch (FileNotFoundException e) { System.out.println ("Cound not open a file for reading"); return; }
// Open the new customer file for writing PrintWriter custWriter = null;
try { custWriter = new PrintWriter (custFile); } catch (FileNotFoundException e) { System.out.println ("Cound not open customer.dat for writing"); return; }
// Process the files try { Customer cust = new Customer (); Transaction trans = new Transaction ();
// Read the first record of both files boolean haveCustomer = cust.readCustomer (custScanner); boolean haveTransaction = trans.readTransaction (transScanner);
// As long as we have customers while (haveCustomer) { // Find transactions that match while (haveTransaction && trans.getId() < cust.getId()) { // We have a transaction, and the id is less than the current // customer id. If we'd had a matching customer for this transaction, // we wouldn't be reading it here, so this is an error. System.out.println ("Transaction not matching any customer: id " + trans.getId() + ", type " + trans.getType() + ", amount " + trans.getAmount()); haveTransaction = trans.readTransaction (transScanner); }
// Process transactions that have the same id while (haveTransaction && trans.getId() == cust.getId()) { if (trans.getType().equals("S")) cust.setBalance(cust.getBalance() - trans.getAmount());
if (trans.getType().equals("P")) cust.setBalance(cust.getBalance() + trans.getAmount());
// By the time we get here, we've run out of transactions for // the current customer, so let's write out the customer to // the new customer.dat cust.writeCustomer (custWriter);
// And read in the next customer to process haveCustomer = cust.readCustomer (custScanner); }
// At this point, we've read through the entire oldcustomer.dat file // We might still have unmatched transactions left over where the // transaction id was greater than any of the customer ids, so let's process those
while (trans != null) { System.out.println ("Transaction not matching any customer: id " + trans.getId() + ", type " + trans.getType() + ", amount " + trans.getAmount()); haveTransaction = trans.readTransaction (transScanner); } } catch (Exception e) { // Not the best way to handle this, but okay for this lab e.printStackTrace (); }
// Close the files custScanner.close (); transScanner.close (); custWriter.close ();