注册 登录
编程论坛 JAVA论坛

Java继承类有没有大神帮帮我

HAO遇见 发布于 2023-04-07 15:17, 2253 次点击
定义储蓄罐(封装)   
    a.属性:储蓄金额   
    b.定义方法:   
        1>存钱方法:参数为存钱的金额,判断存钱    的金额必须是正整数,且为10或5的倍数   
        2>取钱方法:有返回值,返回取钱金额,并    且每次取钱必须为2的倍数,否则取钱失败,取钱成功显示总金额   
    c.定义测试类
1 回复
#2
东海ECS2023-04-07 20:44
储蓄罐类的代码如下:

程序代码:

public class SavingsAccount {
    private int balance;

    public SavingsAccount(int balance) {
        this.balance = balance;
    }

    public void deposit(int amount) {
        if (amount > 0 && (amount % 10 == 0 || amount % 5 == 0)) {
            balance += amount;
            System.out.println("成功存入" + amount + "元,当前余额为" + balance + "元");
        } else {
            System.out.println("存入金额必须为正整数且为10或5的倍数");
        }
    }

    public int withdraw(int amount) {
        if (amount % 2 != 0) {
            System.out.println("取款金额必须为2的倍数");
            return 0;
        } else if (amount > balance) {
            System.out.println("余额不足");
            return 0;
        } else {
            balance -= amount;
            System.out.println("成功取出" + amount + "元,当前余额为" + balance + "元");
            return amount;
        }
    }

    public int getBalance() {
        return balance;
    }
}


测试类的代码如下:

程序代码:

public class SavingsAccountTest {
    public static void main(String[] args) {
        SavingsAccount account = new SavingsAccount(1000);
        account.deposit(50);
        account.deposit(15);
        account.deposit(-10);
        account.deposit(7);
        account.deposit(12);
        account.withdraw(5);
        account.withdraw(7);
        account.withdraw(100);
        account.withdraw(20);
        account.withdraw(30);
        System.out.println("当前余额为:" + account.getBalance());
    }
}


输出结果如下:

成功存入50元,当前余额为1050元
存入金额必须为正整数且为10或5的倍数
存入金额必须为正整数且为10或5的倍数
成功存入10元,当前余额为1060元
成功存入12元,当前余额为1072元
成功取出5元,当前余额为1067元
取款金额必须为2的倍数
余额不足
成功取出20元,当前余额为1047元
成功取出30元,当前余额为1017元
当前余额为:1017

1