Bank account program

I am working on a program to simulate bank transactions. I have to ask the user if they want to make a deposit, withdrawal or transfer.

When I deposit a certain amount (for example, 1000), he says that my balance is 1000. Then I ask you to remove a number, for example, 400, which says that my balance is -400. In the end, I thought that maybe I need to check my balance, and then it will give me the correct balance of what should be 600, but it says 0. For example, see this transcript:

screen capture of output

I thought, because in my code (shown below) I made balance = 0, but if I remove = 0 and try to run the program, it says that it needs to be initialized.

I am stuck and I want to understand this. Please do not submit all corrected code. I want to fix it myself and find out!

import java.util.Scanner; public class BankTransactions { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int num; do { double balance = 0; double amount; System.out.println("Type Number"); System.out.println("1. Deposit"); System.out.println("2. Withdrawal"); System.out.println("3. Balance"); System.out.println("4. Exit"); num = scan.nextInt(); if (num == 1) { System.out.println("Enter amount to deposit: "); amount = scan.nextDouble(); // Add the amount to the balance balance += amount; System.out.println("Your balance is"); System.out.println(balance); } else if (num == 2) { System.out.println("Enter amount to withdrawal: "); amount = scan.nextDouble(); // Remove the amount from the balance balance -= amount; System.out.println("Your balance is"); System.out.println(balance); } else if (num == 3) { System.out.println("Your Balance"); System.out.println(balance); } } while (num != 4); System.out.println("Good Bye!"); } } 
+7
java
source share
3 answers

Each time {...} is executed, and {...}, you set the balance = 0. You must take out the loop.

 double balance = 0; do{ ... 
+10
source share

You initialize the balance to 0 in the do loop, so every time it is reset to zero.

Move the line balance = 0 to a position above the while loop.

+3
source share

Each time you start a loop, you set balance to 0 . Move this outside your do loop:

 double balance = 0; double amount; do { /* code */ } while(num != 4); 
+3
source share

All Articles