Person类数组
package ch01;
public class TestPersonArray {
public static void main(String[] args) {
PersonArray pa=new PersonArray();
//创建对象
Person p1=new Person("张三", 20, "男");
Person p2=new Person("李四", 21, "男");
Person p3=new Person("王五", 22, "女");
Person p4=new Person("赵六", 23, "男");
Person p5=new Person("李斯", 25, "男");
//插入操作
pa.insert(p1);
pa.insert(p2);
pa.insert(p3);
pa.insert(p4);
pa.insert(p5);
pa.display();
//删除操作
pa.delete(p4);
pa.display();
pa.delete("李斯");
pa.display();
//修改操作
Person newPerson=new Person("赵娇娇", 24, "女");
pa.change(p1,newPerson);
pa.display();
}
}
package ch01;
public class PersonArray {
//数组
private Person[] arr;
//数组中有效数据的大小
private int elems;
//默认构造函数
public PersonArray(){
arr=new Person[50];
}
public PersonArray(int max) {
arr=new Person[max];
}
//插入数据
public void insert(Person person) {
arr[elems]=person;
elems++;
}
//显示数据
public void display() {
for(int i=0;i<elems;i++){
arr[i].display();
}
System.out.println();
}
//查找数据
public int find(String name){
int i;
for(i=0;i<elems;i++){
if(name.equals(arr[i].getName())){
break;
}
}
if(i==arr.length){
return -1;
}else{
return i;
}
}
//删除数据
public void delete(String name) {
if(find(name)==-1){
System.out.println("查找不到指定数据,删除失败");
}else{
for(int i=find(name);i<elems;i++){
arr[i]=arr[i+1];
}
}
elems--;
}
//删除数据
public void delete(Person person) {
if(find(person.getName())==-1){
System.out.println("查找不到指定数据,删除失败");
}else{
for(int i=find(person.getName());i<elems;i++){
arr[i]=arr[i+1];
}
}
elems--;
}
//修改数据
public void change(Person oddPerson, Person newPerson) {
if(find(oddPerson.getName())==-1){
System.out.println("查找不到指定数据,查找失败");
}else{
arr[find(oddPerson.getName())]=newPerson;
}
}
}
package ch01;
public class Person {
//用户姓名
private String name;
//用户年龄
private int age;
//用户性别
private String sex;
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 String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Person(String name, int age, String sex) {
super();
this.name = name;
this.age = age;
this.sex = sex;
}
public void display(){
System.out.print("姓名"+this.name);
System.out.print("年龄"+this.age);
System.out.print("性别"+this.sex);
System.out.println();
}
}
经典person类