用面向过程的方法实现数组的插入,查找,删除,显示:
这个例子只有一个class, ArrayApp, 也只有一个方法,main(). 这是典型的面向过程的程序:
=======================================================================
class ArrayApp {
public static void main(String[] args) {
long[] arr; // reference to array
arr = new long[100]; // create an array
int nElems = 0; // number of array elements
int j; // loop counter
long searchKey; // key of item to search for
// insert 10 items
arr[0] = 77;
arr[1] = 99;
arr[2] = 44;
arr[3] = 55;
arr[4] = 22;
arr[5] = 88;
arr[6] = 11;
arr[7] = 00;
arr[8] = 66;
arr[9] = 33;
nElems = 10; // now 10 items are in array
// display items
for(j=0; j<nElems;j++) {
System.out.print(arr[j] + " ");
}
System.out.println(" ");
// find item with key 66
searchKey = 66;
for(j=0; j<nElems; j++) {
if(arr[j] == searchKey) {
break;
}
}
if(j == nElems) {
System.out.println("Cannot find " + searchKey);
}
else {
System.out.println("Found " + searchKey);
}
// delete item with key 55
searchKey = 55;
for(j=0; j<nElems; j++) {
if(arr[j] == search) {
break;
}
}
for(int k=j; k<nElems-1; k++) { // move higher ones down
arr[k] = arr[k+1];
}
nElems--; // decrement size
// display items
for(j=0; j<nElems; j++) {
System.out.print(arr[j] + " ");
}
System.out.println(" ");
} // end main
} // end class ArrayApp
The output of the program looks like:
77 99 44 55 22 88 11 0 66 33
Found 66
77 99 44 22 88 11 0 66 33