Lab10 Class
We maintain an array students
of Student
objects to hold the student records. Also, we maintain the number of student records in the variable numStudents
. The fileReader
is the Scanner
object used for reading from the file.
- Perform number of arguments check: Check if the user has entered the
right number of command line arguments needed by the program. We need the
filename, so there must be one parameter passed. If no parameter is passed to
the program, display an appropriate error message and exit.
How will you know how many command line arguments were passed in?
- Assign the file's input stream to the
Scanner
objectfileReader
: The file's input stream is available using aFileInputStream
object, which is initialized using the filename. ThisFileInputStream
object is in turn used to initialize theScanner
object. This code may throw aFileNotFoundException
, so use the appropriate try and catch blocks. In this step, we are creating an object of theScanner
class and assigning it to thefileReader
reference variable.How will you know the name of the file?
- Read the number of student records from the file: The first line
in the file contains the number of students. Store this value as
numStudents
.Which method of the
Scanner
object can you use to read in integer values from the file? - Allocate memory for the array: As we now know the number of student records, we can now create an array with the appropriate size to hold all of the student records.
- Store the students' records: Read from the file line by line using
the
Scanner
object. For every record in the file, create a newStudent
object, initialize its values with those given in the file, and store theStudent
object in thestudents
array.How do you detect the end-of-file?
How do you read the tuple from each line?
- Close the file: Always remember to close the file's input stream
when you are done reading the file.
Which method will you use to close the input stream ?
- Print stored records: Print the information stored in the student
array in the form:
Student name = [name] and id = [id]
Since the catch block is only handling the FileNotFoundException, what will happen if we get some other kind of exception?