编程练习(11)

来源:互联网 发布:mac ae 插件 百度云盘 编辑:程序博客网 时间:2024/05/16 00:30

定义一个类Student,包含三个属性id, name, password,并对属性进行封装,然后完成如下要求:
Student s1 = new Student(); s1.setId(1); s1.setName(“tom”); s1.setPassword(“123456”);
Student s2 = new Student();s2.setId(1); s2.setName(“tom”);
Student s3 = new Student();s3setId(1); s3.setName(“tom”); s3.setPassword(“111111”);

 要求System.out.println(s1),执行语句控制台输出:id=1;name=tom
 要求s1.equals(s2) 返回true ,s1.equals(s3)返回false
 写一个方法Stduent parseStudent(String str)能够将如下格式的字符串”id=2;name=jack;password=pass”转换成一个student对象

package test1;public class Student {    private int id;    private String name;    private String password;    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }    public Student(){}    public Student(int id, String name, String password) {        this.id = id;        this.name = name;        this.password = password;    }    //重写toString()    public  String toString(){        //System.out.println("id="+id+";name="+name);        return ("id="+id+";name="+name+";password="+password);    }    public Student parseStudent(String str){        Student a=new Student();        String data[]=str.split("[;]");        if(data[0]!=null){            a.id=Integer.parseInt(data[0].substring(data[0].indexOf("=")+1));           }        if(data[1]!=null){            a.name=(data[1].substring(data[1].indexOf("=")+1));        }        if(data[2]!=null){            a.password=(data[2].substring(data[2].indexOf("=")+1));         }        return a;    }}
package test1;public class TestStudent {    public static void main(String[] args) {        Student s1=new Student(1,"tom","123456");        System.out.println(s1);        String str=s1.toString();        Student b=s1.parseStudent(str);        System.out.println(b.getId()+","+b.getName()+","+b.getPassword());    }}
原创粉丝点击