// Fig. 15.7: CreditInquiry.java // This program reads a file sequentially and displays the // contents in a text area based on the type of account the // user requests (credit balance, debit balance or zero balance. import java.io.*; import java.awt.*; import java.awt.event.*; import java.text.DecimalFormat; public class CreditInquiry extends Frame implements ActionListener { // application window components private TextArea recordDisplay; private Button done, credit, debit, zero; private Panel buttonPanel; private RandomAccessFile input; private String accountType; public CreditInquiry() { super( "Credit Inquiry Program" ); // Open the file try { input = new RandomAccessFile( "client.dat", "r" ); } catch ( IOException e ) { System.err.println( e.toString() ); System.exit( 1 ); } setSize( 400, 150 ); // create the components of the Frame buttonPanel = new Panel(); credit = new Button( "Credit balances" ); credit.addActionListener( this ); buttonPanel.add( credit ); debit = new Button( "Debit balances" ); debit.addActionListener( this ); buttonPanel.add( debit ); zero = new Button( "Zero balances" ); zero.addActionListener( this ); buttonPanel.add( zero ); done = new Button( "Done" ); done.addActionListener( this ); buttonPanel.add( done ); recordDisplay = new TextArea( 4, 40 ); // add the components to the Frame add( recordDisplay, BorderLayout.NORTH ); add( buttonPanel, BorderLayout.SOUTH ); setVisible( true ); } public void actionPerformed( ActionEvent e ) { if ( e.getSource() != done ) { accountType = e.getActionCommand(); readRecords(); } else { // Close the file try { input.close(); System.exit( 0 ); } catch ( IOException ioe ) { System.err.println( "File not closed properly\n" + ioe.toString() ); System.exit( 1 ); } } } public void readRecords() { int account; String first, last; double balance; DecimalFormat twoDigits = new DecimalFormat( "0.00" ); // input the values from the file try { // to catch IOException try { // to catch EOFException recordDisplay.setText( "The accounts are:\n" ); while ( true ) { account = input.readInt(); first = input.readUTF(); last = input.readUTF(); balance = input.readDouble(); if ( shouldDisplay( balance ) ) recordDisplay.append( account + "\t" + first + "\t" + last + "\t" + twoDigits.format( balance ) + "\n" ); } } catch ( EOFException eof ) { input.seek( 0 ); } } catch ( IOException e ) { System.err.println( "Error during read from file\n" + e.toString() ); System.exit( 1 ); } } public boolean shouldDisplay( double balance ) { if ( accountType.equals( "Credit balances" ) && balance < 0 ) return true; else if ( accountType.equals( "Debit balances" ) && balance > 0 ) return true; else if ( accountType.equals( "Zero balances" ) && balance == 0 ) return true; return false; } // Instantiate a CreditInquiry object and start the program public static void main( String args[] ) { new CreditInquiry(); } }