一:
package cn.tx.demo;
public class person {
private String idcard;
private String name;
private int age;
private int gender;//1:男;2:女
public person(){
}
//创建构造器
public person(String idcard, String name, int age, int gender) {
this.idcard = idcard;
this.name = name;
this.age = age;
this.gender = gender;
}
public String getIdcard() {
return idcard;
}
public void setIdcard(String idcard) {
this.idcard = idcard;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getGender() {
return gender;
}
public void setGender(int gender) {
this.gender = gender;
}
@Override
public String toString() {
return "person{" +
"idcard='" + idcard + '\'' +
", name='" + name + '\'' +
", age=" + age +
", gender=" + gender +
'}';
}
}
二:
package cn.tx.demo;
import java.util.Arrays;
public class StringTest6 {
/* 定义一个方法,传入字符串格式(idcard:name:age:gender)
的分隔形如"10384722312901:kexin:20:1|3219212131312:
hantao:22:1|120121121312:zhangmeiling:21:2".讲该字
符串的分解,将属性赋给定义的person类的对象上并且输出.提示:创建每个
person对象,每个对象都有idcard,name,ags,gender属性.
person个人信息 idcard身份证号,name名字;age年龄;gender性别*/
public static void main(String[] args) {
String s = “10384722312901:kexin:20:1|3219212131312:hantao:22:1|120121121312:zhangmeiling:21:2”;
//根据"|“拆分字符串
String[] s1 = s.split(”\|");
person[] s4 = new person[3];
//拆分结果:System.out.println(Arrays.toString(s1));
//遍历这个数组 fori+回车
for (int i=0;i<s1.length;i++){
//取出这个字符串
String s2 = s1[i];
//打印这个字符串System.out.println(s2);
//创建 person这个对象,在person创建一个默认构造器否则默认构造器会被覆盖;
person p = new person();
//拆分子字符串
String[] s3 = s2.split("\😊;
//System.out.println(Arrays.toString(s3));
p.setIdcard(s3[0]);
p.setName(s3[1]);
//把一个字符串转成int类型
p.setAge(Integer.parseInt(s3[2]));
p.setGender(Integer.parseInt(s3[3]));
//System.out.println§;
// 把创建的person对象放入新建数组中, 在上面new一个数组搜集
s4[i]=p;
}
System.out.println(Arrays.toString(s4));
}
}