Custom-made Java Objects & File I/O
The goals of this lab is to give you practice with:- creating your own java classes
- using arrays
- reading from and writing to files, from your Java program
In particular, we will read information about several students from a file -provided to us-, then we will filter these data according to some criteria -by lecture section, as an example- and finally write the results back to a file.
You will develop this application from scratch. To start, download the folder lab11_programs
from the download directory.
In this folder, you will find a file containing some input data.
Student class
We will define a Java class, namedStudent
, that will allow us to represent
an instance of a student object. For this application, we are interested in the following
piece of data, related to a student instance:
- last name,
- first name,
- year the student belongs to,
- her cs111 lecture section, and
- her lab section.
Instance Variables
What instance variables do we need to have in the Student class?
Constructor(s)
We will provide two constructors for this class:
- The first constructor will create a Student object out of the five components (individual Strings):
first name, last name, year, lecture and lab section.
Here is an example of how this constructor will be called:
Student s1 = new Student("Alexander", "Wendy", "2011", "lec02", "lab03");
- The second constructor will reate a Student object out of one String only. (The usefulness of such a
constructor will become clear later in this lab).
Here is an example invoking this constructor:
Student s2 = new Student("Alexander;Wendy;2011;lec02;lab03;");
Notice the special delimiters (";") within the string argument above! To extract the individual parts within such a string, you need to use the String instance method
split()
.
Instance Methods
It is usually a good practice to make the instance variables private to the class.
In that case, the class implementer should provide "getter methods", so information
about a particular instance of the class can be accessed from outside the class.
In particular, we will define the following public instance methods:getFirstName()
returns the first name of the invoking Student instancegetLastName()
returns the last name of the invoking Student instancegetLab()
returns the lab section of the invoking Student instancegetLecture()
returns the lecture section of the invoking Student instance, andgetYear()
returns the graduation year of the invoking Student instance
toString()
instance method, which returns
a String representation of the invoking object instance. This method is very useful for
testing purposes.
For example, here is a printed representation of an instance of the Student class:
Wendy Alexander year 2012 is in lec02 and lab01
Add a main()
method to your Student.java file, so you can test your code as
you develop it. As always, you should test your code incrementally, as your
Student.java
file grows.
CS111Students class
The purpose of this class is to read information about a group of Student objects from a file, process and manipulate the data according to the user's needs, and write the results out to an output file.
Instance Variables
In this implementation we will use an array to hold the Student instances.
Look up older labs or homework assignments to help you decide about the instance variables
you should add to this class.
Constructor
The constructor should create an array that can hold Student
objects, and populate it with data read from a file in memory, which is passed
as an argument to the constructor.
Use the java Scanner
class to read data from the file.
Before you attempt to write any code, examine the format of the given data file.
Instance Methods
Here are some instance methods you will write in the CS111Students class:getlabGroup()
This instance method takes a lab section (String) as input, and selects the Student records that match the input. It saves the results in a Student array, which is returned by the method. Test this method before moving onto the other tasks.getyearGroup()
This instance method takes the year (String) as input and returns an array with all the student instances that match the input.
Test this method before moving onto the other tasks.fromArrayToFile()
This instance method takes an array of Student objects, and the name of a file, as inputs. It writes the array data into the file, one object per line. If the array contains null objects, these objects should not be written into the file. This is the header of the method:
public void fromArrayToFile(Student[] input, String output)
getyearAndLabGroup()
This instance method takes the year and the lab section (both as Strings) as input and returns an array with all the student instances that match both of the inputs. This is the header of this method:
public Student[] getyearAndLabGroup(String year, String lab)
Test this method before moving onto other code.
Some helpful pointers
-
Remember that
Scanner
is a useful class when reading files, available in the Java API. Check out the methodshasNext()
andnextLine()
in this class. -
The
split()
method in theString
class is very useful when reading from files. - Below is a (silly) example of creating new files using the PrintWriter class.
Q: How to open a file and write to it?
A: First, here's how to open a file called, say, "flowers.txt":PrintWriter writer = new PrintWriter(new File("flowers.txt"));
Second, here's how to write to our "flowers.txt" file:writer.println("daisy"); writer.println("roses"); writer.println("lily"); writer.println("iris");
System.out.println
? Instead of writing to the console, we're writing to a file! )Finally, when you're all done writing to your file, here's how to wrap up:
writer.close();
public void Shopping()throws IOException {
// open a file called "shopping_list.txt" in your current folder
// PicOps.getFolder() ensures that the file is written to your current folder
PrintWriter writer = new PrintWriter(new File(PicOps.getFolder()+"shopping_list.txt"));
writer.println("eggs");
writer.println("milk");
writer.println("chocolate kisses");
writer.println("cupcakes");
writer.println("gingerbread house");
writer.println("*******************");
writer.println("Here comes some counting!");
for (int i=1; i<10; i++) {
writer.println(i);
}
writer.println("This is the end of the list");
writer.close();
}
The code above produces a completely new file called
shopping_list.txt
in the same directory where the
Shopping.java
file exists. The contents of the file look
like this:
eggs milk chocolate kisses cupcakes gingerbread house ******************* Here comes some counting! 1 2 3 4 5 6 7 8 9 This is the end of the list |
Printing an Array Version 2.0
Remember how we went over printing an array in last week's lab? The method shown below is a newer and improved version over last week's code, because thisprintArray
only prints the non-null
objects in the array. It also prints one array element per line (as opposed to the whole array on one single line). Note also how the toString
method from the
Student class is implicitly called via the System.out.println call. Feel free to use
this method in your code today.
public void printArray(Student[] a) {
System.out.print("[");
for (int i=0; i < a.length; i++) {
if (a[i] != null){ // only print out non-null array items
System.out.print(a[i]);
if (i < (a.length-1))
System.out.println(", "); // print commas, but not after last item in array
}
}
System.out.println("]");
}