Copyright © T. H. Merrett
COMP 612 Principles of Database Programming Week 1 4 of 4
/* Program using the "makes" and "makptr" files of the Cars database to find */
/* the parent and children of a given node (e.g., "BUICK") */
import java.io.*;
public class week1j2
{ private static String make="", father="", brother="", son="", kposStr="";
public static void main(String[] args)
{ int cmpr= 0, indx= 0, ptr= 0;
byte fill;
try
{ DataInputStream makptrd = new DataInputStream(new BufferedInputStream(
new FileInputStream("/course/cs612/carsdata/makptr"),2389));
int dsize= makptrd.readInt(), psize= makptrd.readInt(); // sizes
int[] makptr= new int[psize];
int[] faptr= new int[psize];
int[] brptr= new int[psize];
int[] soptr= new int[psize];
int[] kpos= new int[psize];
for(int enumerate= 0; enumerate<psize; enumerate++)
{ makptr[enumerate]= makptrd.readInt();
faptr[enumerate]= makptrd.readInt();
brptr[enumerate]= makptrd.readInt();
soptr[enumerate]= makptrd.readInt();
kpos[enumerate]= makptrd.readInt();
}
makptrd.close();
RandomAccessFile makesd=
new RandomAccessFile("/course/cs612/carsdata/makes", "r");
// :using direct access to makes
String findMake= args[0].trim(); // supplied as argument to call
// sequential search looking up makptr: could use binary search:
for(indx= 0; indx<psize; indx++)
{ makesd.seek(41*makptr[indx]); make= strRead(makesd, 41, true).trim();
cmpr= findMake.compareTo(make.substring(kpos[indx])); // compare Strings
if (cmpr==0) break; // success
else if (cmpr<0) {indx= psize; break;} // end unsuccessfully
}
if (indx==psize) System.out.println(findMake + " not found");
else
{ ptr= faptr[indx];
if (ptr<0) father= "NO PARENT"; else
{ makesd.seek(41*makptr[ptr]); father= strRead(makesd,41,true).trim(); }
System.out.println(findMake + ": " + make + " " + father);
indx= soptr[indx]; // first child
if (indx<0) System.out.print(" NO CHILD"); else
while(indx>=0)
{ makesd.seek(41*makptr[indx]); brother= strRead(makesd,41,true).trim();
System.out.print(" " + brother);
indx= brptr[indx]; // next child
}
System.out.println(" ");
}
}
catch(IOException e)
{ System.out.print("Error: " + e);
System.exit(1);
}
}
private static String strRead(DataInput filed, int size, boolean crlf)
throws IOException
{ byte[] record= new byte[size];
filed.readFully(record, 0, size);
return bytechars.byte2string(record).substring(0, size - (crlf?1:0));
// if reading whole record, it will include crlf; field will not
}
} // class week1j2