Bank Account


Submit solution

Points: 40 (partial)
Time limit: 1.0s
Memory limit: 256M

Authors:
Problem types
Allowed languages
Java 19, Java 8

題目說明

請設計Bank類別,其中包含以下方法:

calculateInterest():計算計息後資產,並回傳double值
                     計息後資產 = 資產 * (1+月利率)

deposit():記錄存款,印出存款後資產,寫System.out.printf("Assets after deposit: $%,.2f\n", assets);

withdraw():記錄提款,印出提款後資產,寫System.out.printf("Assets after withdraw: $%,.2f\n", assets);
            若提款餘額不足,印出"You are BROKE!",並終止程式

主程式須執行以下步驟:

建立Bank物件
接鍵盤輸入的數值資料(資產、月利率,存款1、提款1、存款2、提款2)
使用deposit()、withdraw()執行兩次存款、提款
使用calculateInterest()方法,並印出回傳值,格式使用"Bank statement: $%,.2f\n"

// 【.printf說明】"$"字號、三位一撇、四捨五入到小數第二位

輸入

資產、月利率
存款1、提款1、存款2、提款2

輸出

Bank statement: $資產金額

測試資料0 輸入

1000 0.2
60 900 7500 60

測試資料0 輸出

Assets after deposit: $1,060.00
Assets after withdraw: $160.00
Assets after deposit: $7,660.00
Assets after withdraw: $7,600.00
Bank statement: $9,120.00

測試資料1 輸入

1000 0.5
50 900 750 1500

測試資料1 輸出

Assets after deposit: $1,050.00
Assets after withdraw: $150.00
Assets after deposit: $900.00
You are BROKE!

Comments


  • 0
    scu09156146  commented on May 7, 2024, 5:52 p.m.

    題解

    import java.util.Scanner;
    
    class Bank {
        // Field,定義Bank類別的參數
        private double assets; // 存款本金不可讓外部直接存取,設定成private
        public double monthlyIR;
    
        // Constructor,建構Bank物件
        public Bank(double a, double mIR) {
            assets = a;
            monthlyIR = mIR;
        }
    
        // Method,定義類別的方法:calculateInterest()、deposit()、withdraw()
        public double calculateInterest() { // 計算計息後資產
            return assets * (1 + monthlyIR);
        }
    
        public void deposit(double n) { // 存款
            assets += n;
            System.out.printf("Assets after deposit: $%,.2f\n", assets);
        }
    
        public void withdraw(double n) { // 提款
            if (assets - n < 0) {
                System.out.println("You are BROKE!");
                System.exit(0);
            } else {
                assets -= n;
                System.out.printf("Assets after withdraw: $%,.2f\n", assets);
            }
        }
    
    }
    
    public class BankAccount {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Scanner input = new Scanner(System.in);
    
            Bank myBank = new Bank(input.nextDouble(), input.nextDouble()); // 資產、月利率
    
            myBank.deposit(input.nextDouble());     // 第1筆存款
            myBank.withdraw(input.nextDouble());    // 第1筆提款
            myBank.deposit(input.nextDouble());     // 第2筆存款
            myBank.withdraw(input.nextDouble());    // 第2筆提款
            input.close();
    
            System.out.printf("Bank statement: $%,.2f\n", myBank.calculateInterest());
        }
    
    }