封装的练习

/*
* 创建程序,在其中定义两个类: Account 和AccountTest类体会Java的封装性。
* Account类要求具有属性:
*   姓名(长度为2位3位或4位)
*   余额(必须>20)
*   密码(必须是六位)
* 如果不满足,则给出提示信息,并给默认值,
* 通过setXxx的方法给Account的属性赋值。
* 在AccountTest中测试。
 */

public class Account {
    private String name;
    private double balance;     //balance  余额
    private String pwd;

    public Account() {
    }

    public Account(String name, double balance, String pwd) {
        this.setName(name);
        this.setBalance(balance);
        this.setPwd(pwd);
    }

    public String getName() {
        return name;
    }
    //姓名(长度为2位3位或4位)
    public void setName(String name) {
        if(name.length() >= 2 && name.length() <= 4){
            this.name = name;
        }else {
            System.out.println("输入错误!姓名2-4位,默认为xxx");
            this.name = "xxx";
        }
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        if(balance > 20){
            this.balance = balance;
        }else {
            System.out.println("输入错误!余额必须>20,默认为0");
            this.balance = 0;
        }
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        if (pwd.length() == 6) {
            this.pwd = pwd;
        }else {
            System.out.println("输入错误!密码(必须是六位),默认为123456");
            this.pwd = "123456";
        }
    }

    public void showInfo(){
        System.out.println("姓名: " + name + " 余额: " + balance + " 密码: " + pwd);
    }
}

public class AccountTest {
    public static void main(String[] args) {
        Account account1 = new Account();
        account1.setName("张三");
        account1.setBalance(200);
        account1.setPwd("123456");
        account1.showInfo();
        System.out.println("===========================================");
        Account account2 = new Account();
        account2.setName("张");
        account2.setBalance(19.5);
        account2.setPwd("12345");
        account2.showInfo();
    }
}

请添加图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值