+-------------+--------------------------------+-------+
| ID | Name | level |
+-------------+--------------------------------+-------+
10 chars 30 chars 4 chars
|
|
class StudentRecord // Format of a student record
{
String ID;
String name;
String level;
}
public class LookupStuFile
{
public static void main(String[] args) throws IOException
{
Scanner in = new Scanner(System.in);
DataFile myFile = new DataFile("student-file"); // Open student-file
StudentRecord x = new StudentRecord(); // Used to store data from file
/* ====================================================
Main processing loop: repeat forever
==================================================== */
while ( true )
{
String s;
/* ========================================
Read in the ID that you want to look up
======================================== */
System.out.print("Enter ID that you want to find: ");
s = in.nextLine(); // Read in the search ID
/* ==================================================
Rewind to file to the beginning before searching
================================================== */
myFile.rewind(); // Reset file to start
/* -------------------------------------------------
Read all records and compare with search value
------------------------------------------------- */
while ( true )
{
try
{
/* ====================================
Read ONE record
==================================== */
x.ID = myFile.ReadString(10); // Read in 10 char and store in x.ID
x.name = myFile.ReadString(30);
x.level = myFile.ReadString(4);
/* -------------------------------------
Compare x.ID with the search value s
Note: x.ID is a String !
-------------------------------------- */
if ( s.equals(x.ID) )
{
/* --------------------------------------------
Print record found
-------------------------------------------- */
System.out.println(">> Found: " + x.ID + ", "
+ x.name + ", " + x.level + "\n");
break; // Quit search
}
}
catch ( IOException e )
{
/* ===========================================
This exception is raised when we reach
the END of the file... (search fails !!!)
============================================ */
System.out.println("Not found !\n");
break; // Exit loop: no more data !!!
}
}
}
}
}
|
How to run the program:
|
Demo:
cd /home/cs377001/demo/Phys-Data-Dependance/file1 java LookupStuFile |