CS111 2010

Lab 11

Wed Nov. 24, 2010

Custom-made Java Objects & File I/O

The goals of this lab is to give you practice with:

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, named Student, 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:
  1. last name,
  2. first name,
  3. year the student belongs to,
  4. her cs111 lecture section, and
  5. her lab section.
All of the above pieces of information will be represented as strings.

Instance Variables

What instance variables do we need to have in the Student class?

Constructor(s)

We will provide two constructors for this class:

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:
We highly recommend that you write the 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:

Some helpful pointers

  1. Remember that Scanner is a useful class when reading files, available in the Java API. Check out the methods hasNext() and nextLine() in this class.
  2. The split() method in the String class is very useful when reading from files.
  3. 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");
    
    (Note: doesn't that look a lot like 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();
    
Let's put these steps together to write a silly Shopping method:


        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 this printArray 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("]");
  }