| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1687 人关注过本帖
标题:Java继承类有没有大神帮帮我
只看楼主 加入收藏
HAO遇见
Rank: 1
等 级:新手上路
帖 子:5
专家分:0
注 册:2023-4-7
结帖率:100%
收藏
已结贴  问题点数:20 回复次数:1 
Java继承类有没有大神帮帮我
定义储蓄罐(封装)   
    a.属性:储蓄金额   
    b.定义方法:   
        1>存钱方法:参数为存钱的金额,判断存钱    的金额必须是正整数,且为10或5的倍数   
        2>取钱方法:有返回值,返回取钱金额,并    且每次取钱必须为2的倍数,否则取钱失败,取钱成功显示总金额   
    c.定义测试类
搜索更多相关主题的帖子: 定义 继承 Java 方法 金额 
2023-04-07 15:17
东海ECS
Rank: 16Rank: 16Rank: 16Rank: 16
来 自:Python
等 级:版主
威 望:32
帖 子:412
专家分:1646
注 册:2023-1-24
收藏
得分:20 
储蓄罐类的代码如下:

程序代码:
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


会当凌绝顶,一览众山小.
2023-04-07 20:44
快速回复:Java继承类有没有大神帮帮我
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.011054 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved