?
Solved

How can I make my code create the new.txt file it suppose to match

Posted on 2008-10-28
3
Medium Priority
?
736 Views
Last Modified: 2013-12-17
CreateData.java  Running this will creates your oldmast.txt and trans.txt text test files
FileMatchTest.java  Running this will test your FileMatch functionality which will reconcile the transactions for accounts to create newmast.txt and log.txt
Currently the newmast.txt and log.txt are not being built.  Not so sure why.
public class TransactionRecord {
 
private int account; 
 
private double amount; 
 
 
// no-argument constructor calls other constructor with default values 
 
public TransactionRecord() 
 
{ 
 
this( 0, 0.0 ); 
 
} // end no-argument TransactionRecord 
 
 
// initialize a record 
 
public TransactionRecord( int acct, double amt ) 
 
{ 
 
setAccount( acct ); 
 
setAmount( amt ); 
 
} // end two-argument TransactionRecord 
 
 
// set account number 
 
public void setAccount( int acct ) 
 
 
{ 
 
account = acct; 
 
} // end method setAccount 
 
 
// get account number 
 
public int getAccount() 
 
{ 
 
return account; 
 
} // end method getAccount 
 
 
// set amount 
 
public void setAmount( double amt ) 
 
{ 
 
amount = amt; 
 
} // end method setAmount 
 
 
// get amount 
 
public double getAmount() 
 
{ 
 
return amount; 
 
} // end method getAmount 
 
} // end class TransactionRecord
 
public class AccountRecord {
// A class that represents one record of information. 
 
private int account; 
private String firstName; 
private String lastName; 
private double balance; 
 
// no-argument constructor calls other constructor with default values 
public AccountRecord() 
 
{ 
 
this( 0, "", "", 0.0 ); // call four-argument constructor 
 
} // end no-argument AccountRecord constructor 
 
 
// initialize a record 
 
public AccountRecord( int acct, String first, String last, double bal ) 
 
{ 
 
setAccount( acct ); 
 
setFirstName( first ); 
 
setLastName( last ); 
 
setBalance( bal ); 
 
} // end four-argument AccountRecord constructor 
 
 
// add a transaction to an account record 
 
public void combine( TransactionRecord transaction ) 
 
{ 
 
balance = balance + transaction.getAmount(); 
 
} // end method combine 
 
 
// set account number 
 
public void setAccount( int acct ) 
 
{ 
 
account = acct; 
 
} // end method setAccount 
 
 
// get account number 
 
public int getAccount() 
 
{ 
 
return account; 
 
} // end method getAccount 
 
 
// set first name 
 
public void setFirstName( String first ) 
 
{ 
 
firstName = first; 
 
} // end method setFirstName 
 
 
// get first name 
 
public String getFirstName() 
 
{ 
 
return firstName; 
 
} // end method getFirstName 
 
 
// set last name 
 
public void setLastName( String last ) 
 
{ 
 
lastName = last; 
 
} // end method setLastName 
 
 
// get last name 
 
public String getLastName() 
 
{ 
 
return lastName; 
 
} // end method getLastName 
 
 
// set balance 
 
public void setBalance( double bal ) 
 
{ 
 
balance = bal; 
 
} // end method setBalance 
 
 
// get balance 
 
public double getBalance() 
 
{ 
 
return balance; 
 
} // end method getBalance 
 
} // end class AccountRecord 
 
 
public class CreateData {
 
// Create data to put into an account file and a transactions file. 
    private Formatter outOldMaster;
    private Formatter outTransaction;
 
    public CreateData() {
        System.out.println("\n\nCreating data files\n");
 
        openFiles();
        CreateData();
    }
 
    private void openFiles() {
        try {
            outOldMaster = new Formatter("oldmast.txt");
            outTransaction = new Formatter("trans.txt");
            System.out.println("Files created\n");
 
        }// end try
        catch (SecurityException securityException) {
            System.err.println("You do not have write access to this file.");
 
            System.exit(1);
        }// end catch
        catch (FileNotFoundException fileNotFoundException) {
            System.err.println("Error creating file.");
            System.exit(1);
        }// end catch               
    }
 
    private void CreateData() {
        AccountRecord accounts[] = new AccountRecord[4];
        /**
         * increase the size of the array for new transaction elements
         */
        TransactionRecord transactions[] = new TransactionRecord[4];
            System.out.println("Populating data files\n");        
 
        // creates account records
 
        accounts[0] = new AccountRecord(100, "Alan", "Jones", 348.17);
        accounts[1] = new AccountRecord(300, "Mary", "Smith", 27.19);
        accounts[2] = new AccountRecord(500, "Sam", "Sharp", 0.00);
        accounts[3] = new AccountRecord(700, "Suzy", "Green", -14.22);
 
        // creates transaction records
 
        transactions[0] = new TransactionRecord(100, 27.14);
        transactions[1] = new TransactionRecord(300, 62.11);
        transactions[2] = new TransactionRecord(400, 100.56);
        transactions[3] = new TransactionRecord(900, 82.17);
        /**
         * Add new transaction elements from book
         */
 
        try {
            for (int i = 0; i < accounts.length; i++) {
                outOldMaster.format("%d %s %s %.2f\n",
                        accounts[i].getAccount(), accounts[i].getFirstName(),
                        accounts[i].getLastName(), accounts[i].getBalance());
            }// end for
 
            if (outOldMaster != null) {
                outOldMaster.close();
            }
 
            for (int i = 0; i < transactions.length; i++) {
                outTransaction.format("%d %.2f\n",
                        transactions[i].getAccount(),
                        transactions[i].getAmount());
            }// end for
 
            if (outTransaction != null) {
                outTransaction.close();
            }
            System.out.println("Done populating data files\n");
        } catch (FormatterClosedException formatterClosedException) {
            System.err.println("Error writing to file.");
        } catch (NoSuchElementException elementException) {
            System.err.println("Invalidarray.");
        }
    }
 
    public static void main(String args[]) {
        new CreateData();
    } // end main
} // end class CreateData 
 
import java.io.File;
import java.util.Formatter;
import java.util.FormatterClosedException;
import java.util.IllegalFormatException;
import java.util.NoSuchElementException;
import java.util.Scanner;
 
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
 
/**
 *
 * @author 
 */
public class FileMatch {
 
 
    private static Scanner inOldMaster;
    private static Scanner inTransaction;
    private static Formatter outNewMaster;
    private static Formatter logFile;
    private static TransactionRecord transaction;
    private static AccountRecord account;
 
    public FileMatch() {
        transaction = new TransactionRecord();
        account = new AccountRecord();
    } // end FileMatch constructor 
 
    public void openFiles() {
        try {
// file streams for input and output files 
            inOldMaster = new Scanner(new File("oldmast.txt"));
            inTransaction = new Scanner(new File("trans.txt"));
            outNewMaster = new Formatter("newmast.txt");
            logFile = new Formatter("log.txt");
        } // end try 
        catch (Exception exception) {
            System.err.println("Error opening the files.");
        } // end catch 
    } // end method openFiles 
/**
 * New method outputData()
 * Takes two ArrayLists as argument
 * Output to files 
 * 
 */
    
    /** void processFiles()
     * method algorithm changes to populate ArrayLists
     * Then compare ArrayList elements
     * outputing data to file by passing ArrayLists
     * to outputData()
     */
    public void processFiles() {
        int transactionAccountNumber;
        int accountNumber;
        try // block for reading/writing all records 
        {
            /**
             * this will be a while loop
             * to read the whole file into
             * an ArrayList
             */
// get a transaction record and its account number 
            transaction = getTransactionRecord();
// if the transaction is null, we are done 
            if (transaction == null) {
                return;
            }
            
            /**
             * Carefull here
             */
            transactionAccountNumber = transaction.getAccount();
// get an account record and its account number 
            account = getAccountRecord();
// if the account is null, we are done 
            if (account == null) {
                return;
            }
            
            /**
             * This will be a while loop
             * to read the whole file into
             * an ArrayList
             */
            accountNumber = account.getAccount();
            
            /**
             * Not needed
             */
            while (accountNumber != 0) {
                
                /**
                 * Change to compare ArrayList elements
                 * matching account ids
                 */
                while (accountNumber < transactionAccountNumber) {
// there is no transaction for this account 
                    
                    /**
                     * Following changes to populate ArrayList
                     */
                    outNewMaster.format("%d %s %s %.2f\n",
                            account.getAccount(), account.getFirstName(),
                            account.getLastName(), account.getBalance());
                   
                    account = getAccountRecord(); // get a new account 
                    if (account == null) {
                        return;
                    }
                    
                    
                    accountNumber = account.getAccount();
                } // end while 
// if there is a transaction for this account 
                if (accountNumber == transactionAccountNumber) {
// combine the records 
                    account.combine(transaction);
// write to the master file 
                    
                    /**
                     * Following changes to populate ArrayList
                     * instead of outputing immediately to file
                     */
                    outNewMaster.format("%d %s %s %.2f\n",
                            account.getAccount(), account.getFirstName(),
                            account.getLastName(), account.getBalance());
                    // get a new transaction 
                    transaction = getTransactionRecord();
                    if (transaction == null) {
                        return;
                    }
                    transactionAccountNumber = transaction.getAccount();
// get a new account 
                    account = getAccountRecord();
                    if (account == null) {
                        return;
                    }
                    accountNumber = account.getAccount();
                } // end if 
                while (transactionAccountNumber < accountNumber) {
// there is no account for this transaction 
                    logFile.format("%s %d\n",
                            "Unmatched transaction record for account number",
                            transactionAccountNumber);
// get a new transaction 
                    transaction = getTransactionRecord();
                    if (transaction == null) {
                        return;
                    }
                    transactionAccountNumber = transaction.getAccount();
                } // end while 
            } // end outer while
        } // end try 
        catch (FormatterClosedException closedException) {
            System.err.println(
                    "Error writing to file - file has been closed.");
            System.exit(1);
        } // end catch 
        catch (IllegalFormatException formatException) {
            System.err.println("Error with output.");
            System.exit(1);
        } // end catch 
    } // end method processFiles 
 
    public void closeFiles() {
        try // close the files 
        {
            if (inTransaction != null) {
                inTransaction.close();
            }
            if (outNewMaster != null) {
                outNewMaster.close();
            }
            if (inOldMaster != null) {
                inOldMaster.close();
            }
            if (logFile != null) {
                logFile.close();
            }
 
        } // end try 
        catch (Exception exception) {
            System.err.println("Error closing the files.");
            System.exit(1);
        } // end catch 
    } // end method closeFiles 
 
// get a transaction record 
    private TransactionRecord getTransactionRecord() {
// try to read the record 
        try {
            if (inTransaction.hasNext()) {
                transaction.setAccount(inTransaction.nextInt());
                transaction.setAmount(inTransaction.nextDouble());
                return transaction;
            } // end if 
            else // we have hit end of transaction file 
            {
// these remaining accounts have 
                while (inOldMaster.hasNext()) {
                    account.setAccount(inOldMaster.nextInt());
                    account.setFirstName(inOldMaster.next());
                    account.setLastName(inOldMaster.next());
                    account.setBalance(inOldMaster.nextDouble());
// store in new master 
                    outNewMaster.format("%d %s %s %.2f\n",
                            account.getAccount(), account.getFirstName(),
                            account.getLastName(), account.getBalance());
                } // end while 
            } // end else 
        } // end try 
        catch (FormatterClosedException closedException) {
            System.err.println("Error writing to file - file has been closed.");
            System.exit(1);
        }// end catch 
        catch (IllegalFormatException formatException) {
            System.err.println("Error with output.");
            System.exit(1);
        } // end catch 
        catch (NoSuchElementException elementException) {
            System.err.println("Invalid input from file.");
        } // end catch 
// return null - no more records 
        return null;
    } // end method getTransactionRecord 
    
// get an account record 
    private AccountRecord getAccountRecord() {
        try // try to read an account record 
        {
            if (inOldMaster.hasNext()) {
                account.setAccount(inOldMaster.nextInt());
                account.setFirstName(inOldMaster.next());
                account.setLastName(inOldMaster.next());
                account.setBalance(inOldMaster.nextDouble());
                return account;
            } // end if 
            else // we have hit end of old master file 
            {
                logFile.format("%s %d\n",
                        "Unmatched transaction record for account number",
                        transaction.getAccount());
// these records are transactions without accounts 
                while (inTransaction.hasNext()) {
                    transaction.setAccount(inTransaction.nextInt());
                    transaction.setAmount(inTransaction.nextDouble());
                } // end while 
            } // end else 
        } // end try 
        catch (FormatterClosedException closedException) {
            System.err.println(
                    "Error writing to file - file has been closed.");
            System.exit(1);
        } // end catch 
        catch (IllegalFormatException formatException) {
            System.err.println("Error with output.");
            System.exit(1);
        } // end catch 
        catch (NoSuchElementException elementException) {
            System.err.println("Invalid input from file.");
        } // end catch 
        return null;
    // end method getAccountRecord 
    } // end class FileMatch 
}
 
public class FileMatchTest 
{
 
public static void main( String args[] ) 
 
{ 
 
FileMatch application = new FileMatch(); 
 
 
application.openFiles(); 
 
application.processFiles(); 
 
application.closeFiles(); 
 
} // end main 
 
} // end class FileMatchTest

Open in new window

0
Comment
Question by:sexy10
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 14

Accepted Solution

by:
Farzad Akbarnejad earned 2000 total points
ID: 22828752
Hello,
Use flush method to write buffered string to disk. Call flush method before closing your output streams.

    public void closeFiles() {
        try // close the files
        {
            if (inTransaction != null) {
                inTransaction.close();
            }
            if (outNewMaster != null) {
                outNewMaster.flush();
                outNewMaster.close();
            }
            if (inOldMaster != null) {
                inOldMaster.close();
            }
            if (logFile != null) {
                logFile.flush();
                logFile.close();
            }

        } // end try
        catch (Exception exception) {
            System.err.println("Error closing the files.");
            System.exit(1);
        } // end catch

    } // end method closeFiles

-FA
0
 

Author Comment

by:sexy10
ID: 22859864
The code did not compile.  The compilation of all the files I attached are suppose to calculate addidional values and create a log.txt, new.txt, trans.txt and old.txt files, and is not happening.
0
 
LVL 14

Expert Comment

by:Farzad Akbarnejad
ID: 22873899
Hello,
It seems that your project is created by NetBeans. If you can, zip your project and upload it to site so I can open and debug it.

-FA
0

Featured Post

Get MySQL database support online, now!

At Percona’s web store you can order your MySQL database support needs in minutes. No hassles, no fuss, just pick and click. Pay online with a credit card.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

If your app took Google’s lash recently, here are the 5 most likely reasons.
There are many software programs on offer that will claim to magically speed up your computer. The best advice I can give you is to avoid them like the plague, because they will often cause far more problems than they solve. Try some of these "do it…
The viewer will learn how to use and create new code templates in NetBeans IDE 8.0 for Windows.
XMind Plus helps organize all details/aspects of any project from large to small in an orderly and concise manner. If you are working on a complex project, use this micro tutorial to show you how to make a basic flow chart. The software is free when…
Suggested Courses

801 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question