Hints for Homework 1

There was a discussion in class of how to write the homework program. I would like to summarize a few of the points and add an additional hint.

Instance Variables

It was noted that (at least) two instance variables will be needed in the class RememberStrings:

      int currentIndex = 0 ;
      String [] words = new String[100] ;
Add methods addWord(String newWord) and printWords(). Overall, the structure of the class will be:
    class RememberStrings
    {
       // the two instance variables shown above

       void addWord(String newWord)
       {
          // add code here
       }

       void printWords()
       {
          // add code here
       }
    }

The class RememberStringsTest

You should make a separate class to hold the public static void main method, called RememberStringsTest. It will instance a RememberString object and then feed it strings, one by one.

      class RememberStringsTest
      {
         public static void main(String [] args)
         {
             RememberStrings rs = new RememberStrings() ;
             // now do rs.addWord(s) on every string s that
             // you read from the keyboard.
             // after each rs.addWord(s), do a printWords().
         }
       }

Reading an Input Line

Create a DataInputStream:

     DataInputStream dis = new DataInputStream( System.in ) ;
Then you can read a string from the DataInputStream object using the method readLine():
     String s ;
     s = dis.readLine() ; // dis is the DataInputStreamObject from above
If the result of readLine is null, then you have hit an End Of File, and you should break out of the program. Else s is a string of input read from the keyboard, to process.

One detail, readLine() throws in an exception if something goes wrong. What is an exception? The code finds something wrong and it wants to return "exceptionally" from the method. The important thing is that you have to handle the exception. To do this, enclose the readLine() method in a try-catch block, which "catches" the exception and handles it.

This all said, here is the class RememberStringsTest:

    class RememberStringsTest
    {
        public static void main(String [] args)
        {
             RememberStrings rs = new RememberStrings() ;
             DataInputString dis = new DataInputString(System.in) ;
             try 
             {
                 while ( true )
                 {
                        // readLine
                        // make decision to exit or not
                        // addWord
                        // printWords 
                 } 
             } catch ( IOException ioe ) { }
        }
    }

Note: Students have brought to my attention that the use of the method readLine for a DataInputStream is deprecated and shoud be replaced by BufferedReader.readLine(). See Sun's official documentation for further discussion.