I was doing my 2nd assignment to create a bank program using Java.
I got a problem when I run a few times.
For example, I entered the starting amount as $50000.
Then, I choose withdraw. I tried to enter withdrawal amount as $5000.
Then, I choose to check balance, and it says $50000 instead of $45000.
If someone check the code whether there is a problem.
package sean_lab2;
import javax.swing.*;
public class Sean_LAB2
{
public static void main (String[] args)
{
double bal; // Balance of savings account
int sel = 0; // Menu selection
bal = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter your starting amount (in $):", "Enter starting amount", JOptionPane.QUESTION_MESSAGE));
while (sel != 4)
{
sel = Integer.parseInt(JOptionPane.showInputDialog(null, "Select an option: \n" +
"1. Withdraw \n" +
"2. Deposit \n" +
"3. Check balance \n" +
"4. Exit" ));
switch(sel)
{
case 1:
withdraw(bal);
break;
case 2:
deposit(bal);
break;
case 3:
CheckBalance(bal);
break;
default:
JOptionPane.showMessageDialog(null, "Thank you for using the program.");
System.exit(0);
}
}
}
public static double withdraw (double bal)
{
double withdrawAmt; // Amount to withdraw
withdrawAmt = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter amount to withdraw (in $):", "Withdraw", JOptionPane.QUESTION_MESSAGE));
while (bal < withdrawAmt)
{
JOptionPane.showMessageDialog(null, "The amount you've entered to withdraw is more than your savings balance.\nPlease re-enter.", "Withdraw", JOptionPane.ERROR_MESSAGE);
withdrawAmt = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter amount to withdraw (in $):", "Withdraw", JOptionPane.QUESTION_MESSAGE));
}
bal -= withdrawAmt;
return bal;
}
public static double deposit (double bal)
{
double depositAmt; // Amount to deposit
depositAmt = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter amount to deposit (in $):", "Deposit", JOptionPane.QUESTION_MESSAGE));
while (depositAmt <= 0)
{
JOptionPane.showMessageDialog(null, "The amount you've entered to deposit is a negative amount or zero.\nPlease re-enter.", "Deposit", JOptionPane.ERROR_MESSAGE);
depositAmt = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter amount to deposit (in $):", "Deposit", JOptionPane.QUESTION_MESSAGE));
}
bal += depositAmt;
return bal;
}
public static void CheckBalance (double bal)
{
JOptionPane.showMessageDialog(null, "Your balance is: $" +bal, "Check Balance", JOptionPane.INFORMATION_MESSAGE);
}
}