//Person类
public class Person {
private String lastName;
private String firstName;
private int age;

//person构造器
public Person(String lastName, String firstName, int age) {
this.lastName = lastName;
this.firstName = firstName;
this.age = age;
}

//打印person信息
void displayPerson() {
System.out.println("Name:" + firstName + " " + lastName + " " + "age:" + age);
}

//返回lastname
String getLastName() {
return lastName;
}
}

//
class ClassDataArray {
private Person[] a; //reference to array
private int nElems ; //number of data items

public ClassDataArray(int max) { //constructor
a = new Person[max]; //create the array
nElems = 0; //no items yet
}

public Person find(String searchName) {
int i;
for (i = 0; i < nElems; i++) //for each element
if (a[i].getLastName().equals(searchName))//found item?
break; //exit loop before end
if (i == nElems) //gone to end?
return null; //yes,can't find it
else
return a[i]; //no, find it


}

public void insert(String last, String first, int age) {

a[nElems] = new Person(last, first, age);
nElems++; //increment size
}

public boolean delete(String searchName) {//delete person from array

int i;
for (i = 0; i < nElems; i++) //look for it
if (a[i].getLastName().equals(searchName))
break;

if (i == nElems) //can't find it
return false;
else {//found it
for (int j = i; j < nElems; j++)//shift down
a[j] = a[j + 1];
nElems--; //decrement size
return true;
}

}

public void displayA() { //display array contents

int i;
for (i = 0; i < nElems; i++) { //for each element
a[i].displayPerson(); //display it
}
}
}

class ClassDataApp {
public static void main(String[] args) {
int maxSize = 100;
ClassDataArray arr;
arr = new ClassDataArray(maxSize);
arr.insert("Evans", "Patty", 24);
arr.insert("Smith", "Lorraine", 37);
arr.insert("Yee", "Tom", 43);
arr.insert("Adams", "Henry", 63);
arr.insert("Hashinoto", "Sato", 21);
arr.insert("Stimson", "Henry", 29);
arr.insert("Velasquez", "Jose", 72);
arr.insert("Lanarque", "Henry", 53);
arr.insert("Wang", "Minh", 22);
arr.insert("Creswell", "Lucinda", 18);

arr.displayA();

String searchKey = "Stimson";
Person found;
found = arr.find(searchKey);
if (found != null) {
System.out.println("Found ");
found.displayPerson();
} else
System.out.println("Can't find" + searchKey);

System.out.println("Deleting Smith,Yee and Creswell");
arr.delete("Smith");
arr.delete("Yee");
arr.delete("Creswell");

arr.displayA();
}
}
 
posted on 2017-11-21 14:56  学点小技术做点小事情  阅读(122)  评论(0编辑  收藏  举报