把这个程序写出来了,很有成就感。求鼓励下学弟我。
/*
编写一个学生封装类Student[包含name,age,sex,address私有属性,共有的方法]
创建3个Student对象,并给其属性赋值
定义功能:把Student对象转为字符串,最后打印字符串
要求输出字符串格式如下:
{[name=”xxx”,age=xx,sex=’x’,address=”xxxxx”],
[name=”xxx”,age=xx,sex=’x’,address=”xxxxx”],
[ name=”xxx”,age=xx,sex=’x’,address=”xxxxx”]}*/
class Student{
private String name;
private int age;
private char sex;
private String address;
public String getName() {
return name;
}
public Student(String name, int age, char sex, String address) {
super();
this.name = name;
this.age = age;
this.sex = sex;
this.address = address;
}
public Student() {}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
public class StudentToString {
public static void main(String[] args) {
Student stu1=new Student("牛顿", 22,'男' ,"英国");
Student stu2=new Student("爱因斯坦", 29,'男' ,"德国");
Student stu3=new Student("居里夫人", 26,'女' ,"波兰");
Student[] stus=new Student[3];
stus[0]=stu1;
stus[1]=stu2;
stus[2]=stu3;
System.out.println(studentToString(stus));
}
public static String studentToString(Student[] stus){
StringBuilder sb=new StringBuilder("{");
//遍历数组
for (int i = 0; i < stus.length; i++) {
Student stu=stus[i];
sb.append("[name=\""+stu.getName()+"\",age="+stu.getAge()+",sex=\""+
stu.getSex()+"\",address=\""+stu.getAddress()+"\"],");
}
sb.replace(sb.length()-1, sb.length(), "}");
return sb.toString();
}
}
|
|