Results 1 to 15 of 15
- 08-12-2011, 03:57 PM #1
Member
- Join Date
- Aug 2011
- Posts
- 8
- Rep Power
- 0
Creating a transfer function for a ATM simulation
Hi guys, im fairly new to java so im not sure on what to do here. What i want to be able to do is be able to transfer say $100 from this account to another account.I have attached the code below.Any help would be greatly appreciated. =).
ATM Testing.zip
- 08-12-2011, 04:13 PM #2
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7
Please paste the code in code tags instead. Many people will be hesitant with attachments. To add code tags type
[code]
YOUR CODE HERE
[/code]
- 08-12-2011, 04:20 PM #3
Member
- Join Date
- Aug 2011
- Posts
- 8
- Rep Power
- 0
Oh ok then. =)
[ATM GUI]
/* ATM.java requires: ATMLogin.java ATMDataFile.java
ATMData.txt*/
[ATMDataFile]/* ATMDataFile Loads bank account data from a text file into memoryJava Code:import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; public class ATM { static JFrame ATMFrame = new JFrame("ATM"); // ATM constructor public ATM() throws IOException { // Instantiate a new ATMDataFile object called atmData ATMDataFile atmData = new ATMDataFile(); loginGUI(); ATMFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ATMFrame.setSize(400,200); } public static void loginGUI() { //Create and set up the ATM Login content pane. final ATMLogin loginContentPane = new ATMLogin(ATMFrame); ATMFrame.setContentPane(loginContentPane); //Make sure the focus goes to the right component //whenever the ATMFrame is initially given the focus. ATMFrame.addWindowListener(new WindowAdapter() { public void windowActivated(WindowEvent e) { loginContentPane.resetFocus(); } }); //Display the pane. ATMFrame.setVisible(true); } public static void chooserGUI() { //Create and set up the ATM Login content pane. final ATMChooser chooserPane = new ATMChooser(ATMFrame); ATMFrame.setContentPane(chooserPane); //Display the window. ATMFrame.setVisible(true); } public static void withdrawGUI() { //Create and set up the ATM Login content pane. final ATMWithdraw withdrawContentPane = new ATMWithdraw(ATMFrame); withdrawContentPane.setLayout(new GridLayout(0,1)); ATMFrame.setContentPane(withdrawContentPane); //Display the window. ATMFrame.setVisible(true); } public static void depositGUI() { //Create and set up the ATM Login content pane. final ATMDeposit depositContentPane = new ATMDeposit(ATMFrame); depositContentPane.setLayout(new GridLayout(0,1)); ATMFrame.setContentPane(depositContentPane); //Display the window. ATMFrame.setVisible(true); } public static void transferGUI() { //Create and set up the ATM Login content pane. final ATMTransfer transferContentPane = new ATMTransfer(ATMFrame); transferContentPane.setLayout(new GridLayout(0,1)); ATMFrame.setContentPane(transferContentPane); //Display the window. ATMFrame.setVisible(true); } public static void balanceGUI() { //Create and set up the ATM Login content pane. final ATMBalance balanceContentPane = new ATMBalance(ATMFrame); balanceContentPane.setLayout(new GridLayout(3,1)); ATMFrame.setContentPane(balanceContentPane); //Display the window. ATMFrame.setVisible(true); } public static void main(String[] args) throws IOException { ATM atm = new ATM(); } }
for use by other objects that change things (balance etc).
If no text file exists one is created with details for one account.
Data is held by a two dimensional array (account_inf[][]) where
account_inf[0][0] is 1st account number
account_inf[0][1] is 1st account pasword
account_inf[0][2] is 1st account balance
account_inf[1][0] is 2nd account number
account_inf[1][1] is 2st account pasword etc...*/
[ATMTransfer]/*+++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++Java Code:import java.io.*; import java.util.Scanner; public class ATMDataFile { public static String datafilename = "ATMData.txt"; public static int lines = 0; // Number of lines in ATMdata.txt public static int lineNo; // Line number of the opperative account // Create a File object called "datafile" to see if "ATMdata.txt" exists static File datafile = new File(datafilename); // Declare a 2 dimensional array to hold account details // First three values are only used if no datafile exists. static String[][] account_inf = {{"John","Savings","12345","4444","100"}, {"Jack","Manager","54321","0000","100"}, {null,null,null}, {null,null,null}, {null,null,null}}; public ATMDataFile() throws IOException { // If ATMdata.txt exists run loadData method if (datafile.exists()) { loadData(); // Debug code //writeFile(); // If no datfile exists run the writeNewFile method } else { writeNewFile(); } } // method for loading ATMdata.txt to a 2 dimensional array static void loadData()throws IOException { Scanner scan = null; BufferedReader read = null; try { // Create Scanner (reads text files one space delimeted element at a time) // and BufferedReader (reads contents of a text file into memory) objects scan = new Scanner(new BufferedReader(new FileReader(datafile.getName()))); read = new BufferedReader(new FileReader(datafile.getName())); // Count the number of lines in ATMdata.txt String l; while ((l = read.readLine()) != null) { lines ++ ; } // Debug code System.out.println ("Lines =" +lines); // Populate the 2 dimensional array account_inf with contents of // ATMdata.txt. account_inf[0][0] is 1st account number // account_inf[0][1] is 1st account pasword // account_inf[0][2] is 1st account balance // account_inf[1][0] is 2nd account number etc... for(int i=0; i<=lines-1; i++){ for(int j=0; j<=4; j++){ account_inf[i][j] = scan.next(); // Debug code System.out.print(" [" +i +"][" +j +"]=" +account_inf[i][j]); } // Debug code System.out.println(); } } catch (IOException e) { System.err.println("Caught IOException: " + e.getMessage()); } finally { if (scan != null) { scan.close(); } } } static void writeNewFile()throws IOException { String name = account_inf[0][0]; String account_typ = account_inf[0][1]; String account_no = account_inf[0][2]; String password = account_inf[0][3]; String balance = account_inf[0][4]; PrintWriter out = null; try { // Create an output stream to write to ATMdata.txt out = new PrintWriter(datafile.getName()); // Write the first three values of the two dimensional array // to the ATMdata.txt file. out.format ("%s %s %s %s %s", account_inf[0][0], account_inf[0][1], account_inf[0][2], account_inf[0][3], account_inf[0][4]); } finally { if (out != null) { out.close(); } } } static void writeFile()throws IOException { PrintWriter out = null; try { // Create an output stream to write to ATMdata.txt out = new PrintWriter(datafile.getName()); // Write account_inf[][] to disk for (int i = 0; i<=lines-1; i++) { out.format ("%s %s %s %s %s", account_inf[i][0], account_inf[i][1], account_inf[i][2], account_inf[i][3], account_inf[i][4]); out.println(); } } finally { if (out != null) { out.close(); } } } static String getPin(String account_id){ String pin = ""; for (int i = 0; i <= lines ; i++) { if (account_id.equals(account_inf[i][2])) { pin = account_inf[i][3]; lineNo = i; // Debug code System.out.println("pinString="+pin); break; } } return pin; } static String doDeposits(String amount){ // Deposit cash -- called from ATMDeposits String newBalance = ""; // Turn Strings to doubles for arithmatic double depositsAmount= (new Double(amount)).doubleValue(); double currentBalance= (new Double(account_inf[lineNo][4])).doubleValue(); // Get the new balance as a string & update the account_inf array newBalance = Double.toString (currentBalance + depositsAmount); account_inf[lineNo][4] = newBalance; return newBalance; } static String doWithdrawl(String amount){ // Withdraw cash -- called from ATMWithdrawl String newBalance = ""; // Turn Strings to doubles for arithmatic double withdrawlAmount= (new Double(amount)).doubleValue(); double currentBalance= (new Double(account_inf[lineNo][4])).doubleValue(); // Get the new balance as a string & update the account_inf array newBalance = Double.toString (currentBalance - withdrawlAmount); account_inf[lineNo][4] = newBalance; return newBalance; } static String doTransfer(String amount){ // Withdraw cash -- called from ATMWithdrawl String newBalance = ""; // Turn Strings to doubles for arithmatic double transferAmount= (new Double(amount)).doubleValue(); double currentBalance= (new Double(account_inf[lineNo][4])).doubleValue(); // Get the new balance as a string & update the account_inf array newBalance = Double.toString (currentBalance - transferAmount); account_inf[lineNo][4] = newBalance; return newBalance; } static String getBalance() { return account_inf[lineNo][4]; } }
*DESCRIPTION:
*ATMTransfer is a subtype of the Java JPanel class which is a GUI
* container which is contained by a JFrame (ATM) and contains the
* Text, buttons and entry fields of the GUI.
*
* CALLED BY:
* Clicking the Transferl button on the ATMChooser JPanel object calls the
* ATMTransferl method on the ATM object which in turn invokes this class
*
* ACTIONS:
* The ATMTransfer JPanel allows the user to select an ammount to Transfer
* by either mouse clicking on an ammount button or typing in an amount to
* Transfer.
*
* CALLS:
* This class calls the doTransferl method on the ATMData object to action
* the Transferl then calls the balanceGUI method on the ATM object to display
* the new balance.
++++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++*/
Java Code:// Import GUI, IO and math libraries import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.math.*; // Class declaration establishing ATMTransfer as a subtype of // JPanel (a content pane to be displayed inside a JFrame) // elements of a graphic user interface (GUI) // impliments ActionListener statement indicates that it uses // the Java actionlistener class public class ATMTransfer extends JPanel implements ActionListener { // Declare string variables for use in GUI private static String AU20 = "20"; private static String AU50 = "50"; private static String AU100 = "100"; private static String AU200 = "200"; private static String AU300 = "300"; private static String OTHER = "other"; private static String AMOUNT = "amount"; private static String ACCOUNT_INF = "account_inf"; // Declare JButton variables for use in GUI private static JButton au20Button, au50Button, au100Button, au200Button,au300Button, otherButton; // Declare object variables for use in GUI private JFrame controllingFrame; //needed for dialogs protected JTextField amountTextField; protected JTextField account_infTextField; protected JLabel amountLabel; protected JLabel account_infLabel; private ATMDataFile atmData; private ATM atm; // Constructor method - called from ATM with ATMframe as the argument f // an ATMTransferl object is created as a subtype of a JPanel public ATMTransfer(JFrame f) { controllingFrame = f; JComponent titlePane = createTitlePane(); add(titlePane); // add the titlepane to the ATMTransfer JPanel // Call the createButtonPanel method to populate the button pane JComponent buttonPane = createButtonPanel(); add(buttonPane); // Call the createBotTextPane method to populate the text box pane pane JComponent botTextPane = createBotTextPane(); add(botTextPane); add(botTextPane); } // "actionPerformed" method - reads the action command "cmd" // set by the button and text field components and selected // by the users mouse click or text entry // and selects the action to perform public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); //gets "cmd" if button clicked String input = amountTextField.getText(); //gets "input" from text entry if (OTHER.equals(cmd)){ // Other amount button pressed. amountTextField.setEnabled(true); amountTextField.setEnabled(true);// enable text entry amountLabel.setEnabled(true); account_infTextField.setEnabled(true); account_infLabel.setEnabled(true); au20Button.setEnabled(false); // disable (grey out) other buttons au50Button.setEnabled(false); au100Button.setEnabled(false); au200Button.setEnabled(false); au300Button.setEnabled(false); otherButton.setEnabled(false); amountTextField.requestFocusInWindow(); //set focus to text entry } else if (AMOUNT.equals(cmd)) { // User enters other amount. //Test if the entered ammount is a multiple of $20 // by using the "mod" opperation to divide by 20 and find the remainder BigInteger remainder = (new BigInteger(input)).mod (new BigInteger("20")); // Test if remainder is "0" if (remainder.equals((new BigInteger("0")))) { // Yes it's a multiple JOptionPane.showMessageDialog(controllingFrame, // pop up a success message "$"+input +" is a multiple of $20\n" +"Well done!!"); // Invoke the "tryTransfers" method // with the entered ammount as the argument tryTransfers(input); } else { // Not a multiple of $20 JOptionPane.showMessageDialog(controllingFrame, // pop up a failure message "$"+input +" is not a multiple of $20\n" +"This is not a multiple of $20,Please try again.", "Error Message", JOptionPane.ERROR_MESSAGE); } } else { // User pressed a value button int buttonValue = (new Integer(cmd)).intValue(); switch (buttonValue) { case 20: tryTransfers(cmd); break; case 50: tryTransfers(cmd); break; case 100: tryTransfers(cmd); break; case 200: tryTransfers(cmd); break; case 300: tryTransfers(cmd); break; } } } // "tryTransferl" method calls ATMData.doTransferl and process results protected void tryTransfers(String in) { // run the doTransferl method on the ATMData object // this method returns the amount remaining in the account // which is stored in the newBalance variable String newBalance = atmData.doTransfer(in); if (newBalance.isEmpty()) { //Not enough cash // Display an error message JOptionPane.showMessageDialog(controllingFrame, "You don't have $"+in +" to Transfer.\n" +"Sorry mate please try again.", "Error Message", JOptionPane.ERROR_MESSAGE); } else { // Transferl OK // Go back to the balance display screen by invoking the // balanceGUI method on the atm object atm.balanceGUI(); } } // Methods to populate the title pane, button pane // and bottom text entry pane with text, buttons and // text entry components. These methods are called from the // class constructor method which also adds them to the atm frame. // These are written as seperate methods to seperate the "messy and confusing" // GUI componentry from the actual processes conducted by this class. protected JComponent createTitlePane() { JPanel t = new JPanel(new GridLayout(0,1)); JLabel topLabel = new JLabel("Select amount to Transfer: "); t.add(topLabel); return (t); } protected JComponent createButtonPanel() { JPanel p = new JPanel(new GridLayout(0,2)); au20Button = new JButton("$20"); au20Button.setActionCommand(AU20); au20Button.addActionListener(this); p.add(au20Button); au200Button = new JButton("$200"); au200Button.setActionCommand(AU200); au200Button.addActionListener(this); p.add(au200Button); au50Button = new JButton("$50"); au50Button.setActionCommand(AU50); au50Button.addActionListener(this); p.add(au50Button); au300Button = new JButton("$300"); au300Button.setActionCommand(AU300); au300Button.addActionListener(this); p.add(au300Button); au100Button = new JButton("$100"); au100Button.setActionCommand(AU100); au100Button.addActionListener(this); p.add(au100Button); otherButton = new JButton("Choose another amount"); otherButton.setActionCommand(OTHER); otherButton.addActionListener(this); p.add(otherButton); return p; } protected JComponent createBotTextPane() { JPanel b = new JPanel(new FlowLayout(FlowLayout.TRAILING)); amountTextField = new JTextField(5); amountTextField.setActionCommand(AMOUNT); amountTextField.addActionListener(this); amountTextField.setEnabled(false); amountLabel = new JLabel("Type Transfer amount (multiples of $20 only)"); amountLabel.setLabelFor(amountTextField); amountLabel.setEnabled(false); account_infTextField = new JTextField(8); account_infTextField.setActionCommand(ACCOUNT_INF); account_infTextField.addActionListener(this); account_infTextField.setEnabled(true); account_infLabel = new JLabel("Enter the account number"); account_infLabel.setLabelFor(account_infTextField); account_infLabel.setEnabled(true); b.add(amountLabel); b.add(amountTextField); b.add(account_infLabel); b.add(account_infTextField); return (b); } }Last edited by sunde887; 08-12-2011 at 04:26 PM.
- 08-12-2011, 04:30 PM #4
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7
You also will get more help by explaining what exactly is challenging you. Perhaps a SSCCE will also help here. Most likely not many people will read through so much code.
- 08-12-2011, 04:36 PM #5
Member
- Join Date
- Aug 2011
- Posts
- 8
- Rep Power
- 0
Well what im trying to do is be able to transfer say $100 from one account to another, but i have no clue on what type of method to use...
- 08-12-2011, 04:39 PM #6
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7
You should really have an Account class, rather than a 2d array which creates the accounts. Then the account class can have a method like
Java Code:public void transferMoney(int amount, Account from, Account to){...}
- 08-12-2011, 04:47 PM #7
Member
- Join Date
- Aug 2011
- Posts
- 8
- Rep Power
- 0
Hmm good point, but if i were to create a separate class for the accounts that would mean the code would need to be dramatically changed? hahaha excuse my beginner talk =/
- 08-12-2011, 04:59 PM #8
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7
The code will have to be changed yes, but it's a good way to learn. Making your code as object based as possible(oop), makes for easier to maintain, change, and fix code errors.
- 08-12-2011, 05:19 PM #9
Member
- Join Date
- Aug 2011
- Posts
- 8
- Rep Power
- 0
I've become a bit lost where to start ='(
- 08-12-2011, 05:25 PM #10
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7
Try creating an Account class which has all the information about the account, and methods to do whatever is necessary to the account, deposit, withdraw, checkBalance, transfer, etc
Then the GUI will basically be used to manage accounts.
- 08-13-2011, 08:29 AM #11
Member
- Join Date
- Aug 2011
- Posts
- 8
- Rep Power
- 0
Would it be like as below?
[Account]
Java Code:import java.util.Scanner; public class Account { private String accountName; private int password; private double balanceAmount; private static int accountNumberCounter = 100; private int accountNumber; Scanner userInput = new Scanner(System.in); Account bob = new Account("Jake Styles", 1111, 100.00); Account mary = new Account("Jenny Smith", 2222, 200.00); Account sally = new Account("John Green", 1111, 300.00); public Account(String name, int pword, double balance) { accountName = name; password = pword; balanceAmount = balance; accountNumberCounter++; accountNumber = accountNumberCounter; // This shows we have brought the information over from the BankApp class System.out.println(accountName + " " + password + " " + balanceAmount); System.out.println("Option " + BankApp.option + " was selected."); } public int acctNum() { return accountNumber; } public double getBalance() { return balanceAmount; } public void setBalance(double balance) { balanceAmount = balance; } public void withdraw(double withdrawAmount) { if (withdrawAmount > balanceAmount) { System.out .println("You do not have enough money in your account, try again"); } else { balanceAmount = balanceAmount - withdrawAmount; } } public void deposit(double depositAmount) { balanceAmount = balanceAmount + depositAmount; } }Last edited by sunde887; 08-13-2011 at 10:46 AM. Reason: Code tags added, [code]...[/code]
- 08-13-2011, 10:45 AM #12
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7
Looks good, although I would be hesitant about allowing so much freedom in the setBalance method. What if some creep decided to come along and do
?Java Code:account.setBalance(Integer.MIN_VALUE);
Perhaps you can limit the account balances changes. For example, you could provide the following three methors
This way you can check what is being done to the account. Perhaps if someone tries something likeJava Code:public void deposit(int amount){...} public void withdraw(int amount){...} public void transfer(Account from, Account to, int amount){...}
you can do something likeJava Code:account.deposit(Integer.MIN_VALUE);
This way the only balance changes will be made from within the class in the way you want it to happen.Java Code:public void deposit(int amount){ if(! amount > 0) throw new IllegalArgumentException("Can't deposit negative amounts"); ... }
So my suggestion: get rid of the setter, and add these three methods I've provided to you. You may want to get rid of the 3 instances of the account which are instance variables of the class, since they aren't really members of account. When you develop ATMMachine(or whatever it ends up being named), it will create the Accounts and manage them.
- 08-13-2011, 01:28 PM #13
Member
- Join Date
- Aug 2011
- Posts
- 8
- Rep Power
- 0
Hey mate, thankyou for the advice =). Below is the updated code based on your advice, i have added the three methods however when i go to compile the code I get '.class' expected. I assume i have made a beginner mistake? p.s i have marked the line in red
[Account]
Java Code:public class Account { private String accountName; private int password; private double balanceAmount; private static int accountNumberCounter = 100; private int accountNumber; public Account(String name, int pword, double balance) { accountName = name; password = pword; balanceAmount = balance; accountNumberCounter++; accountNumber = accountNumberCounter; // This shows we have brought the information over from the BankApp class System.out.println(accountName + " " + password + " " + balanceAmount); System.out.println("Option " + BankApp.option + " was selected."); } public int acctNum() { return accountNumber; } public double getBalance() { return balanceAmount; } public void withdraw(int amount) { [COLOR="red"]if (int) amount > balanceAmount) {[/COLOR] System.out .println("You do not have enough money in your account, try again"); } else { balanceAmount = balanceAmount - ! amount; } } public void deposit(int amount) { balanceAmount = balanceAmount + "int amou"; if(! amount > 0) throw new IllegalArgumentException("Can't deposit negative amounts") } public void transfer(Account from, Account to, int amount) }Last edited by sunde887; 08-13-2011 at 01:39 PM. Reason: Code tags added, [code]...[/code]
- 08-13-2011, 01:44 PM #14
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7
Evaluate the code. Does this look correctJava Code:public void withdraw(int amount) { if (int) amount > balanceAmount) { System.out .println("You do not have enough money in your account, try again"); } else { balanceAmount = balanceAmount - ! amount; } } public void deposit(int amount) { balanceAmount = balanceAmount + "int amou"; if(! amount > 0) throw new IllegalArgumentException("Can't deposit negative amounts") }
Scrutinize this section and you will notice something wrong.Java Code:if (int) booleanExpression)
When it comes to the deposit code
Must be the first thing the code tests. Why bother continuing if they tried to deposit an incorrect number? You also don't need to use an exception, you can use a simple print method, but you have to be careful that you don't continue with modifying the account balance.Java Code:if(! amount > 0) throw new IllegalArgumentException("Can't deposit negative amounts")
- 08-13-2011, 02:16 PM #15
Member
- Join Date
- Aug 2011
- Posts
- 8
- Rep Power
- 0
Similar Threads
-
BPA registration simulation
By noahwhygodwhy in forum New To JavaReplies: 4Last Post: 04-04-2011, 12:47 AM -
Creating Temporary files using the createTempFile function problem.
By ArmenBaba in forum New To JavaReplies: 2Last Post: 08-19-2010, 10:44 AM -
Possible? Callback function passed as arguments to another function
By TreyAU21 in forum Advanced JavaReplies: 3Last Post: 12-04-2009, 03:08 PM -
Creating the evaluation function for Minimax
By matzahboy in forum New To JavaReplies: 7Last Post: 11-05-2009, 03:29 PM -
help creating two classes that function together
By sinreaver in forum New To JavaReplies: 6Last Post: 10-01-2008, 03:44 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks