2013-10-09 107 views
7

我正在製作一個模擬銀行交易的程序。我必須詢問用戶是否要存款,取款或轉賬。銀行賬戶計劃

當我存入一定數量(例如1000)時,它說我的餘額是1000.然後我要求提取一個像400這樣的數字它說我的餘額是-400。一切,我想,也許我要檢查我的天平再經過它會給我的應該是什麼600的正確平衡,但它說0。舉例來說,看到這個成績單:

screen capture of output

我思考,因爲在我的代碼(如下所示)我做了平衡= 0,但如果我把= 0,並嘗試運行該程序它說,它需要進行初始化。

我被卡住了,我想弄明白。請不要發佈更正的整個代碼。我想自己解決並學習!

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!"); 

    } 
} 
+8

切勿使用浮點類型來表示貨幣:http://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent -currency –

回答

10

每當do {...} while {...}被執行時,您正在設置balance = 0。你應該把它帶出循環。

double balance = 0; 

do{ 
... 
+1

+1擊敗我吧 – sameday

+0

感謝您的快速幫助!我知道這將是微小的msitake – Morgan

3

您在do循環內將balance初始化爲0,所以它每次都重置爲零。

將行平衡= 0移動到while循環上方。

3

每次運行循環時,您都將balance設置爲0。移動給你的do外循環:

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