Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 23 of 23

Thread: Threads in BankAccount program

  1. #1
    Junior Member
    Join Date
    Mar 2012
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Threads in BankAccount program

    Hi, I am having to create a bank account program were there are inputs and withdraws from the account. The inputs only come in every so often, and the same with withdraws. For instance weekly wage is 2000, which comes in once a week. But a heating oil cost withdraws £250 every 3 weeks. I have to use multi threading to show the updated balance, and have to use 1 second as equal to 1 week. When I run the program I am not getting the updated balance.

    Wage Received should deposit £2000 into account every week (1 second)
    Oil Bill should withdraw £250 every 3 weeks (3 seconds)
    Food Bill should withdraw £600 every week (1 second)
    Electricity Bill should withdraw 50 every week (1 second)
    Entertainment Bill should withdraw £400 every week (4 seconds)

    package BankAccount;
     
    /**
     *
     * A small class to handle deposits and withdrawls from a bank account
     * 
     */
    //A bank account has a balance that can be changed by deposits and withdrawals.
     
    public class BankAccount
    {  
       private double balance;
     
       //Constructs a bank account with a zero balance.
     
       public BankAccount()
       {   
          balance = 0;
       }
     
       //Constructs a bank account with a given balance.
     
       public BankAccount(double initialBalance)
       {   
          balance = initialBalance;
       }
     
       //Deposits money into the bank account.
     
       public void deposit(int addAmount, String name)
       {  
          double newBalance = balance + addAmount;
          balance = newBalance;
          System.out.println("Balance is now " + balance);
       }
     
       //Withdraws money from the bank account.
     
       public void withdraw(int takeAmount, String name)
       {   
          double newBalance = balance - takeAmount;
          balance = newBalance;
          System.out.println("Balance is now " + balance);
       }
     
       //Gets the current balance of the bank account.
     
       public double getBalance()
       {   
          return balance;
       }
    }

    package BankAccount;
     
    import java.util.Random ;
     
    public class Utility implements Runnable
    {
        private int transAmt;
        private String transType;
        private String typeOfUtility ;
        private int howOften;
     
        BankAccount bankacc = new BankAccount();
     
        public Utility(String name, int frequency, String type, int amount)
        {
            typeOfUtility = name ;
            howOften = frequency;
            transType = type;
            transAmt = amount;
        }
     
        public void run()
        {
            //do (true) {
            try
            {
                while(true){
     
                if(transType == "Deposit"){
                    bankacc.deposit(transAmt, typeOfUtility);
                } else if (transType == "Withdrawl"){
                    bankacc.withdraw(transAmt, typeOfUtility);
                }
    //            System.out.println(typeOfUtility + " going to work for " + workingTime + " milliseconds");
    //            if deposit call deposit(transamt, typeofutility)
    //            else call withdrawl
                   Thread.sleep(howOften) ;
             // End of try block
            catch(InterruptedException ex)
            {
                System.out.println(typeOfUtility + " Terminated early") ;
            } // End of Catch clause
                }
    //        System.out.println(typeOfUtility + " has finished") ;
        //} 
            }  
        }
    }

    package BankAccount;
     
    import java.lang.Thread ;
     
    public class main {
     
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            // TODO code application logic here
            System.out.println("Bank Account Scenario");
     
            // Create each of the threads
            Thread wageReceived = new Thread(new Utility("Wage Received", 1000, "Deposit", 2000));
            Thread oilBill = new Thread(new Utility("Oil Bill", 3000, "Withdrawl", 250)) ;
            Thread foodBill = new Thread(new Utility("Food Bill", 1000, "Withdrawl", 600));
            Thread electricityBill = new Thread(new Utility("Electricity Bill", 1000, "Withdrawl", 50));
            Thread entertainmentBill = new Thread(new Utility("Entertainment Bill", 1000, "Withdrawl", 400));       
     
            // Get the threads going
            wageReceived.start() ;
            oilBill.start() ;
            foodBill.start();
            electricityBill.start();
            entertainmentBill.start();
     
            System.out.println("Week is now underway") ; 
     
     
        }
    }

    For my output I am not getting the correct balance. When it adds 2000 the balance will be 2000 which is correct, then it should take off food bill and electricity but instead of taking them off the 2000 it will output a minus number.

    Anyone got any tips?

    Thanks


  2. #2
    Think of me.... Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Pakistan
    Posts
    1,136
    My Mood
    Grumpy
    Thanks
    20
    Thanked 82 Times in 78 Posts
    Blog Entries
    1

    Default Re: Threads in BankAccount program

    Kindly paste here the exact output you are getting and your expected output as well.
    Anyone who stops learning is old, whether at twenty or eighty. Anyone who keeps learning stays young. The greatest thing in life is to keep your mind young.

    - Henry Ford

  3. #3
    Junior Member
    Join Date
    Mar 2012
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Threads in BankAccount program

    This is what I am getting:
    Bank Account Scenario
    Week is now underway
    Balance is now 2000.0
    Balance is now -250.0
    Balance is now -600.0
    Balance is now -50.0
    Balance is now -400.0

    I expect to get:
    Balance is now 2000
    Balance is now 1750
    Balance is now 1150
    Balance is now 1100
    Balance is now 700

    It is not updating the balance each time, instead it is just saying how much I have withdrawn or deposited. It should be updating with the balance, from what goes in before it. For example, week 1 i get 2000 in, so balance should be 2000, then it should take out the withdraws depending on the week.

    Thanks for your help.

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Threads in BankAccount program

    Try debugging the code to see what it is doing. The way I do it is by adding println statements that print out all the values of the variables that the program uses. If you know what the program is supposed to do, then the printed values of the variables will show you where the program is going wrong so you can fix it.
    Print out every variable as it is changed. Be sure to add an ID String to the print out so you know what variable is being printed and where it is being printed.


    Your posted code does not compile without errors. You need to fix the errors.
    Last edited by Norm; March 13th, 2012 at 06:57 AM.

  5. #5
    Think of me.... Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Pakistan
    Posts
    1,136
    My Mood
    Grumpy
    Thanks
    20
    Thanked 82 Times in 78 Posts
    Blog Entries
    1

    Default Re: Threads in BankAccount program

    You must not let all the threads to access the values at same time. You have to look here Interactive Programming In Java
    Anyone who stops learning is old, whether at twenty or eighty. Anyone who keeps learning stays young. The greatest thing in life is to keep your mind young.

    - Henry Ford

  6. #6
    Forum VIP
    Join Date
    Oct 2010
    Posts
    275
    My Mood
    Cool
    Thanks
    32
    Thanked 54 Times in 47 Posts
    Blog Entries
    2

    Default Re: Threads in BankAccount program

    Using this many threads is going to have a lot of volatility, which is probably going to make it hard to debug. A better way to do it might be to have one thread that updates all the different entities every second, and another one being the UI thread. This could be done with an interface or an object or something which the game logic thread accepts in a list of some sort. EG: [In psuedo code]

    interface Updatable
      method update(current time)

    class UpdatableImpl implements Updatable
      variable delay
      variable last updated
      method update(current time)
        if current time is less than (last updated - delay)
          return
       else
         doUpdate()
     
      method doUpdate()
        throw UnsupportedOperationException("That operation is not supported")
    or something like that, so your updating thread could just delay every x ms and call update(System.currentTimeMillis()) iteratively through the array of Updatable objects

    Note: You should only call System.currentTimeMillis once each loop, for more consistency

    BTW I made a blog post about thread volatility: http://www.javaprogrammingforums.com/entry.php?b=63
    Last edited by Tjstretch; March 13th, 2012 at 02:27 PM.

  7. #7
    Junior Member
    Join Date
    Mar 2012
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Threads in BankAccount program

    OK Thanks folks, think I have it working now.

    Anyway, do you know how I could do a loop so that it does this over and over again for 24 seconds, and then stops?

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Threads in BankAccount program

    Use the time System.currentTimeMillis() to detect when 24 seconds have passed. Get starting time and then compare current time against that.

  9. #9
    Junior Member
    Join Date
    Mar 2012
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Threads in BankAccount program

    Still needing some help in different program now, but its related. I am using a GUI to ask users to enter some data such as income and outgoings. I have a text field for income and a text field for outgoings. I am wanting to get the balance when users enter values into these fields. The balance will just be income-outgoings.

    Anyway, does anyone know how I store the values that the user enters into these fields so that I can work this out?

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Threads in BankAccount program

    The text fields have methods for getting the values they contain as Strings. You can then convert the Strings into the type of values you want and save those values in class variables that can be used to work with.

  11. #11
    Junior Member
    Join Date
    Mar 2012
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Threads in BankAccount program

    Could you give an example for this sort of code?

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Threads in BankAccount program

    Something like this. Check the API doc for the correct spelling of the method names:

    String val = textField.getTheDataMethod(); // Get contents of the text field
    int intVal = Integer.convertToIntMethod(val); // convert String to int value

  13. #13
    Junior Member
    Join Date
    Mar 2012
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Threads in BankAccount program

    Ok thanks, and then i just refer to it as intVal later then?

  14. #14
    Junior Member
    Join Date
    Mar 2012
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Threads in BankAccount program

    Here is an example of my code:
    income1 = new JTextField();
    income1.setColumns(10);
    String in1Type = income1Type.getText();
    int intIn1Type = Integer.convertToIntMethod(in1Type);

    It is saying that it cant find the convertToIntMethod?

  15. #15
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Threads in BankAccount program

    My code was an example. You need to read the API doc for the Integer class to find the spelling for the method.
    I think it starts with parse....

  16. #16
    Junior Member
    Join Date
    Mar 2012
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Threads in BankAccount program

    Got it now it is parseInt the method. But when I run it I am getting the following error:

    Exception in thread "main" java.lang.NumberFormatException: For input string: ""
    at java.lang.NumberFormatException.forInputString(Num berFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:504)
    at java.lang.Integer.parseInt(Integer.java:527)
    at timerdrivenanimation.ControlPanel.<init>(ControlPa nel.java:101)
    at timerdrivenanimation.MyFrame.<init>(MyFrame.java:3 3)
    at timerdrivenanimation.TimerDrivenAnimation.main(Tim erDrivenAnimation.java:16)
    Java Result: 1

  17. #17
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Threads in BankAccount program

    The error message says that the String being parsed was empty.
    You could test for an empty String before trying to parse it and ask the user to enter a value then exit the method to wait for the user to enter a good value and press a button.

  18. #18
    Junior Member
    Join Date
    Mar 2012
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Threads in BankAccount program

    So what I have to do now is to have a GUI with a number of text fields on it. There will be two income text fields, and 5 outgoingss text fields. With each of these text fields there will be a duration text field. The user enters values into the income and outgoings and into the duration field. There will also be a simulation duration field were the user will enter how many seconds they want the program to run for.

    When the user presses the start button, then the balance should update every second. For example if income1 id £500 and duration 2, then every 2seconds £500 will be added to the bank account. Anyone any ideas on how to do this?

    Thanks

  19. #19
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Threads in BankAccount program

    Look at using the Timer class. It will can your method every time period(2 seconds). In your method you can update the balance field.

  20. #20
    Junior Member
    Join Date
    Mar 2012
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Threads in BankAccount program

    Dont really understand that, could I PM the question to anyone?

  21. #21
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Threads in BankAccount program

    Look at the API doc for the Timer in the swing package. It has a small example of how to use it.

  22. #22
    Junior Member
    Join Date
    Mar 2012
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Threads in BankAccount program

    How do I access API doc?

  23. #23
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Threads in BankAccount program

    Java Platform SE 6
    Find the link for the class in the lower left, click on it and the doc shows in the main frame.

Similar Threads

  1. BankAccount assignment problem
    By ddonn in forum What's Wrong With My Code?
    Replies: 2
    Last Post: November 6th, 2011, 01:04 PM
  2. Problem with threads
    By Shahram in forum Threads
    Replies: 4
    Last Post: October 14th, 2011, 06:43 AM
  3. Threads in Web Crawler
    By relion65 in forum Threads
    Replies: 5
    Last Post: June 28th, 2011, 11:48 PM
  4. threads
    By crazed8s in forum Threads
    Replies: 2
    Last Post: December 14th, 2010, 05:33 AM
  5. threads in gui
    By urosz in forum AWT / Java Swing
    Replies: 1
    Last Post: November 3rd, 2009, 05:20 PM