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)
Code :
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;
}
}
Code :
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") ;
//}
}
}
}
Code :
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
Re: Threads in BankAccount program
Kindly paste here the exact output you are getting and your expected output as well.
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.
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.
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
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]
Code :
interface Updatable
method update(current time)
Code :
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/blogs/tjstretch/63-thread-volatility.html
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?
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.
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?
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.
Re: Threads in BankAccount program
Could you give an example for this sort of code?
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
Re: Threads in BankAccount program
Ok thanks, and then i just refer to it as intVal later then?
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?
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....
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
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.
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
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.
Re: Threads in BankAccount program
Dont really understand that, could I PM the question to anyone?
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.
Re: Threads in BankAccount program
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.