Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Hi, I\'m working my way through a project that would be similar to a bank simula

ID: 3704834 • Letter: H

Question

Hi,

I'm working my way through a project that would be similar to a bank simulation. I've to use a RandomAccessFile to store records of bank accounts. I've created a class to create the accounts and write them to the file and I have a class to read the account and display the account details. The class I've copied below also works for deleting an account. I'm now stuck at trying to figure out how I could make withdrawls or deposits to an account by accepting in an amount from the user and then adding or subtracting this from the balance field in the record.

Hope this nakes sense

Regards

Alex

//this class will allow the user to read data for a particular account

//and delete the account

import java.io.*;

import java.awt.*;

import javax.swing.*;

import java.awt.event.*;

import java.text.DecimalFormat;

public class CreditUnionClose extends JFrame implements ActionListener

{

//create GUI components

private JTextField idField, firstNameField, lastNameField, balanceField, overdraftField;

private JButton closeBut, exitBut;

private RandomAccessFile input, output;

private Record data;

public CreditUnionClose()

{

super ("Close Account");

try

{

//set up files for read & write

input = new RandomAccessFile( "credit1.dat", "rw" );

output = new RandomAccessFile( "credit1.dat", "rw" );

}

catch ( IOException e )

{

System.err.println(e.toString() );

System.exit(1);

}

data = new Record();

//create the components of the Frame

setSize( 600, 300 );

setLayout( new GridLayout(6, 2) );

add( new JLabel( "Account ID Number (1 - 100)" ) );

idField = new JTextField(15);

idField.setEditable( true );

add( idField );

idField.addActionListener(this);

add( new JLabel( "First Name" ) );

firstNameField = new JTextField(15);

firstNameField.setEditable( false );

add( firstNameField );

add( new JLabel( "Last Name" ) );

lastNameField = new JTextField(15);

lastNameField.setEditable( false );

add( lastNameField );

add( new JLabel( "Account Balance" ) );

balanceField = new JTextField(15);

balanceField.setEditable( false );

add( balanceField );

add( new JLabel( "Overdraft Facility" ) );

overdraftField = new JTextField(15);

overdraftField.setEditable( false );

add( overdraftField);

closeBut = new JButton( "Close Account");

closeBut.addActionListener( this );

add(closeBut);

closeBut.setEnabled(false);

exitBut = new JButton( "Exit" );

exitBut.addActionListener( this );

add(exitBut);

setVisible( true );

}

public void actionPerformed( ActionEvent e )

{

//read account details when account number entered

if (! idField.getText().equals(""))

{

readRecord(); //calling readRecord method

closeBut.setEnabled(true);

}

if (e.getSource() == exitBut) //exit maintenance menu

{

setVisible(false);

}

if (e.getSource() == closeBut)

{

try

{

int accountNumber = Integer.parseInt( idField.getText() );

data.setID( 0 );

data.setFirstName( null );

data.setLastName( null);

data.setBalance( 0);

data.setOverdraft( 0);

output.seek( (long) ( accountNumber-1 ) * Record.size() );

data.write( output );

JOptionPane.showMessageDialog(this, "Account has been deleted");

idField.setText("");

firstNameField.setText("");

lastNameField.setText("");

balanceField.setText("");

overdraftField.setText("");

}//end try

catch (NumberFormatException nfe )

{

System.err.println("You must enter an integer account number");

}

catch (IOException io)

{

System.err.println("error during write to file " + io.toString() );

}

}

} //end actionPerformed

public void readRecord()

{

DecimalFormat twoDigits = new DecimalFormat( "0.00" );

try

{

int accountNumber = Integer.parseInt(idField.getText());

if (accountNumber < 1 || accountNumber > 100)

{

JOptionPane.showMessageDialog(this, "Account does not exist");

}

else

{

input.seek( (accountNumber - 1)*Record.size());

data.read(input);

idField.setText(String.valueOf( data.getID() ) );

firstNameField.setText( data.getFirstName() );

lastNameField.setText( data.getLastName() );

balanceField.setText( String.valueOf( twoDigits.format( data.getBalance() ) ) );

overdraftField.setText( String.valueOf(twoDigits.format( data.getOverdraft() ) ) );

}

if (data.getID() == 0)

{

JOptionPane.showMessageDialog(this, "Account does not exist");

idField.setText("");

}

if (data.getBalance() != 0)

{

JOptionPane.showMessageDialog(this, "Balance needs to be Zero before Account can be removed");

idField.setText("");

}

}//end try statement

catch (EOFException eof )

{

closeFile();

}

catch (IOException e )

{

System.err.println("Error during read from file " + e.toString() );

System.exit( 1 );

}

} // end readRecord method

private void closeFile()

{

try

{

input.close();

System.exit( 0 );

}

catch( IOException e)

{

System.err.println( "Error closing file " + e.toString() );

}

}// end closeFile method

public static void main(String [] args)

{

new CreditUnionClose();

}

}

*******************************************************************************************************************************************

UPDATE

*********************************************************************************************************************************************

*********RAF CREATION*********************************************

// This section will create a random access file and
// will write 100 empty records to file.

import java.io.*;

public class CreateRandomFile
{
private Record blank;
private RandomAccessFile file;

public CreateRandomFile()

{
blank = new Record();

try
{

file = new RandomAccessFile( "credit1.dat", "rw" );

for (int i=0; i<100; i++)
blank.write( file );

}

catch(IOException e)

{

System.err.println("File not opened properly " + e.toString() );

System.exit( 1 );

}
}

public static void main( String [] args )

{
CreateRandomFile accounts = new CreateRandomFile();
}

}

*************************************************************************************************************************************************

********RECORD***************************************************

//Initial program for creation of file to contain various accounts

import java.io.*;

import javax.swing.*;

public class Record

{

private int accountid;

private String firstName;

private String lastName;

private double balance;

private double overdraft;

public void read( RandomAccessFile file ) throws IOException

{

accountid = file.readInt();

char first[] = new char[15];

for ( int i=0; i < first.length; i++ )

first[ i ] = file.readChar();

firstName = new String (first);

char last[] = new char[15];

for (int i =0; i<last.length; i++)

last[i] = file.readChar();

lastName = new String (last);

balance = file.readDouble();

overdraft = file.readDouble();

}

public void write( RandomAccessFile file) throws IOException

{

StringBuffer buf;

file.writeInt( accountid );

if (firstName != null)

buf = new StringBuffer( firstName);

else

buf = new StringBuffer( 15 );

buf.setLength( 15 );

file.writeChars( buf.toString() );

if ( lastName != null )

buf = new StringBuffer( lastName );

else

buf = new StringBuffer( 15);

buf.setLength( 15 );

file.writeChars( buf.toString() );

file.writeDouble( balance );

file.writeDouble( overdraft);

}

public void setID( int a ) { accountid = a; }

public int getID() { return accountid;}

public void setFirstName( String f) {firstName = f;}

public String getFirstName() { return firstName; }

public void setLastName ( String l) { lastName = l; }

public String getLastName() { return lastName; }

public void setBalance( double b) {balance = b;}

public double getBalance() {return balance;}

public void setOverdraft( double o) {overdraft = o;}

public double getOverdraft() {return overdraft;}

//determines size (bytes) of each file

public static int size() { return 80;}

}

Explanation / Answer

Warning: Please delete credit1.dat file for the very first time you run this program. Otherwise it gives error

I have modified your program accordingly

//Initial program for creation of file to contain various accounts

import java.io.*;

// to write object of account class in file that class must be serializable

public class Account implements Serializable

{

private int accountid;

private String firstName;

private String lastName;

private double balance;

private double overdraft;

public Account(int aid,String fname,String lname, double bal,double od)

{

setID(aid);

setFirstName(fname);

setLastName(lname);

setBalance(bal);

setOverdraft(od);

}

public void setID( int a ) { accountid = a; }

public int getID() { return accountid;}

public void setFirstName( String f) {firstName = f;}

public String getFirstName() { return firstName; }

public void setLastName ( String l) { lastName = l; }

public String getLastName() { return lastName; }

public void setBalance( double b) {balance = b;}

public double getBalance() {return balance;}

public void setOverdraft( double o) {overdraft = o;}

public double getOverdraft() {return overdraft;}

//determines size (bytes) of each file

public static int size() { return 80;}

}

#################################################################

File IO class

#################################################################

// This class performs io operation of file

import java.io.*;

import java.util.*;

public class FileOperations

{

private Account acc;

private RandomAccessFile file;

public ArrayList<Account> readAccountList()

{

ArrayList<Account> acl = new ArrayList<Account>();

try

{

FileInputStream fi = new FileInputStream(new File("credit1.dat"));

ObjectInputStream oi = new ObjectInputStream(fi);

acl=(ArrayList<Account>) oi.readObject(); // reads object of arraylist from file

oi.close();

fi.close();

}

catch(Exception e)

{

System.err.println("File not opened properly in read " + e.toString() );

System.exit( 1 );

}

return acl; // returns that object

}

public void writeAccountList(ArrayList<Account> aclist)

{

try

{

File file=new File("credit1.dat");

if(!file.exists()) // checks whether a file exists or not. if not exist then creates a new file else opens that file

file.createNewFile();

FileOutputStream f = new FileOutputStream(file);

ObjectOutputStream o = new ObjectOutputStream(f);

// Write object to file

o.writeObject(aclist);

o.close();

f.close();

}

catch(Exception e)

{

System.err.println("File not opened properly in write " + e.toString() );

System.exit( 1 );

}

}

}

###################################################################

Class that manages bank operations

###################################################################

//this class will allow the user to read data for a particular account

//and delete the account

import java.io.*;

import java.awt.*;

import javax.swing.*;

import java.awt.event.*;

import java.text.DecimalFormat;

import java.util.*;

public class CreditUnionClose extends JFrame implements ActionListener

{

//create GUI components

private JTextField idField, firstNameField, lastNameField, balanceField, overdraftField,currField;
private JButton createBut,closeBut, exitBut,transitBut,ptBut;
private JLabel l;
private JRadioButton cr,wd;

private Account acc;
ArrayList<Account> accList;
FileOperations fio;

public CreditUnionClose()

{

super ("Banking");

fio=new FileOperations();

accList = new ArrayList<Account>();

//create the components of the Frame

setSize( 600, 300 );

setLayout( new GridLayout(10, 2) );

add( new JLabel( "Account Number" ) );

idField = new JTextField(15);

idField.setEditable( true );

add( idField );

add( new JLabel( "First Name" ) );

firstNameField = new JTextField(15);

//firstNameField.setEditable( false );

add( firstNameField );

add( new JLabel( "Last Name" ) );

lastNameField = new JTextField(15);

//lastNameField.setEditable( false );

add( lastNameField );

add( new JLabel( "Account Balance" ) );

balanceField = new JTextField(15);

//balanceField.setEditable( false );

add( balanceField );

add( new JLabel( "Overdraft Facility" ) );

overdraftField = new JTextField(15);

//overdraftField.setEditable( false );

add( overdraftField);

createBut = new JButton( "Create Account");

createBut.addActionListener( this );

add(createBut);

closeBut = new JButton( "Close Account");

closeBut.addActionListener( this );

add(closeBut);

exitBut = new JButton( "Exit" );

exitBut.addActionListener( this );

add(exitBut);

transitBut = new JButton( "Transactions" );

transitBut.addActionListener( this );

add(transitBut);

cr=new JRadioButton("credit");   

wd=new JRadioButton("withdraw");

ButtonGroup bg=new ButtonGroup();   

bg.add(cr);bg.add(wd);   

add(cr);add(wd);

cr.setVisible(false);

wd.setVisible(false);

l= new JLabel( "Enter Amount" );

add( l );

l.setVisible(false);

currField = new JTextField(15);

currField.setEditable( true );

currField.setVisible(false);

add( currField );

ptBut = new JButton( "Perform Transaction" );

ptBut.addActionListener( this );

add(ptBut);

ptBut.setVisible(false);

setVisible( true );

this.addWindowListener(new WindowAdapter() {

@Override

public void windowClosing(WindowEvent e) {

// Terminate the program after the close button is clicked.

System.exit(0);

}

});

}

void clearFields()

{

idField.setText("");

firstNameField.setText("");

lastNameField.setText("");

balanceField.setText("");

overdraftField.setText("");

currField.setText("");

}

boolean accountExists(ArrayList<Account> accList,int accountNumber)

{

boolean flag=false;

for(int i=0;i<accList.size();i++)

{

if(accList.get(i).getID() == accountNumber)

flag=true;

}

return flag;

}

public void actionPerformed( ActionEvent e )

{

// creates e new account

if (e.getSource() == createBut) //create button pressed

{

acc = new Account(Integer.parseInt(idField.getText()),firstNameField.getText(),lastNameField.getText(),Double.parseDouble(balanceField.getText()),Double.parseDouble(overdraftField.getText())); // creates an object of account class

File f = new File("credit1.dat");

// checks if file exists or not for the very first account. because initially there is no record in file and you are reading that file so it gives EOF exception

if(f.exists())

accList=fio.readAccountList();

accList.add(acc);

fio.writeAccountList(accList);

JOptionPane.showMessageDialog(this, "Account created successfully");

clearFiels();

}

if (e.getSource() == exitBut) //exit maintenance menu

{

setVisible(false);

System.exit(0);

}

if (e.getSource() == closeBut) //close account button is pressed

{

try

{

int accountNumber = Integer.parseInt( idField.getText() ); //gets account number

accList=fio.readAccountList();

for(int i=0;i<accList.size();i++)

{

if(accList.get(i).getID() == accountNumber) //gets the account with account number specified

{

accList.remove(i); //removes that account

break;

}

}

fio.writeAccountList(accList);

JOptionPane.showMessageDialog(this, "Account has been deleted");

clearFields();

}//end if

else

{

JOptionPane.showMessageDialog(this, "Account not exists");

}

}

catch (NumberFormatException nfe )

{

System.err.println("You must enter an integer account number");

}

}

if (e.getSource() == transitBut) // if selects transaction button then some fields that are not visible gets visible

{

cr.setVisible(true);

wd.setVisible(true);

l.setVisible(true);

currField.setVisible(true);

ptBut.setVisible(true);

}

if (e.getSource() == ptBut)

{

if(idField.getText().equals(""))

{

JOptionPane.showMessageDialog(this, "Please enter account number");

}

else if(cr.isSelected())

{

accList=fio.readAccountList();

int no=Integer.parseInt(idField.getText());

for(int i=0;i<accList.size();i ++)

{

if(accList.get(i).getID()==no)

{

double bal = accList.get(i).getBalance(); // gets current balance of that customer

bal=bal+Double.parseDouble(currField.getText()); //adds the value in balance

accList.get(i).setBalance(bal); // update the balance

firstNameField.setText(accList.get(i).getFirstName());

lastNameField.setText(accList.get(i).getLastName());

balanceField.setText(Double.toString(bal));

overdraftField.setText(Double.toString(accList.get(i).getOverdraft()));

JOptionPane.showMessageDialog(this, "Money credited successfully");

break;

}

}

fio.writeAccountList(accList); // gets update in file

}

else if(wd.isSelected()) // for withdraw

{

accList=fio.readAccountList();

int no=Integer.parseInt(idField.getText());

for(int i=0;i<accList.size();i ++)

{

if(accList.get(i).getID()==no)

{

double bal = accList.get(i).getBalance();

bal=bal-Double.parseDouble(currField.getText());

if(bal>0) //if balance is greater than zero then only update

{

accList.get(i).setBalance(bal);

firstNameField.setText(accList.get(i).getFirstName());

lastNameField.setText(accList.get(i).getLastName());

balanceField.setText(Double.toString(bal));

overdraftField.setText(Double.toString(accList.get(i).getOverdraft()));

JOptionPane.showMessageDialog(this, "Money withdrawed successfully");

fio.writeAccountList(accList);

break;

}

else

JOptionPane.showMessageDialog(this, "You dont have sufficient balance");

}

}

}

else

{

JOptionPane.showMessageDialog(this, "Please select any options");

}

}

} //end actionPerformed

public static void main(String [] args)

{

new CreditUnionClose();

}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote