java-面向对象中级-封装(案列2)

面向对象中级-封装(案列2)

题目

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

Account类

package com.hspedu.encap;

import java.util.Scanner;

/**
 * 创建程序,在其中定义两个类:Account和AccountTest类体会Java的封装性。
 * Account类要求具有属性:姓名(长度为2位3位或4位)、余额(必须>20)、
 * 密码(必须是六位), 如果不满足,则给出提示信息,并给默认值(程序员自己定)
 * 通过setXxx的方法给Account 的属性赋值。
 * 在AccountTest中测试
 */
public class Account {
  //为了封装,将三个属性设置为private
    private String name;
    private double 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;
    }

    public void setName(String name) {
        if (name.length() >= 2 && name.length() <= 4) {
            this.name = name;
        }else {
            System.out.println("你输入的名字不符规则!");
            this.name = "无名";
        }
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        if (balance>20){
            this.balance = balance;
        }else {
            System.out.println("余额必须大于20,默认取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 shouInfo() {
        Scanner scanner = new Scanner(System.in);
        //可以增加权限的校验
        System.out.println("请输入密码:");
        int key = scanner.nextInt();
        if (key == 886699 ){
            System.out.println("账号信息 name=" + name + "余额" + balance +"密码" +pwd);
        }else{
            System.out.println("你无权查看");
        }

    }

}


AccountTest

package com.hspedu.encap;

public class TestAccount {
    public static void main(String[] args) {
        //创建Account
        Account account = new Account();
        account.setName("guo");
        account.setBalance(100);
        account.setPwd("886699");

        account.shouInfo();
    }
}

正确运行结果
在这里插入图片描述
密码错误时候
在这里插入图片描述
不符题意时
在这里插入图片描述
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值