CPSC 124, Winter 1998
Sample Answers to Lab 10


This page contains a sample answer to the exercise from Lab #10 in CPSC 124: Introductory Programming, Winter 1998. See the information page for that course for more information.


The exercise that you were to turn in for this lab involved modifying the program CodeMain.java. The first modification was to enable decoding of files in that program. Once you did this, you were to decode and read the file mission.txt, which contained instructions for doing the rest of the lab. Here is a decoded version of mission.txt:

        ...so, you've successfully decoded the rest of the lab.

        To finish the lab, you have to implement the "Decode a
        page from the Internet" option in the "Files Starter"
        project.  To do this, you should create a new static method
        called doWebPage() and call it from the appropriate place 
        in the menu() method.  The new method can be a copy of
        the doFile() method, except for two things.  First, it
        doesn't have a parameter.  Second, the input stream will
        read its data from a file on the World Wide Web instead
        of from a file on the computer's hard drive.

        Instead of reading the name of the source file, the
        doWebPage() method should read the URL of the source
        file.  This will be a String specifying the address of
        the coded file on the World Wide Web.  From this
        String, the method can create an object belonging to
        a class called URL.  If webPageAddress is the String
        that contains the Web address, then the URL object can
        be created with the command

                 URL url = new URL(webPageAddress);

        Once you have this object, you can create the input stream
        to read the data from it by saying:

                 in = new DataInputStream( url.openStream() );
                 
        Note that BOTH of these two commands can throw IOExceptions,
        so you have to put both of them inside a try statement that
        catches this exception.

        *** FUDGE FACTOR ALERT ***

          Because of what sems to be an error in Microsoft's version
          of Java, some extra stuff is added on the the front of the
          actual contents of the Web page.  This messes up the
          decryption!  To fix this, you have to read up to the
          first empty line in the file and discard what you find.
          You can do this with the following lines just after
          "in = new DataInputStream( url.openStream() );" :

                 String junk;
                 do {
                    junk = in.readLine();
                 } while (junk != null && !junk.equals(""));

        **************************

        Once you have implemented the doWebPage() method, use
        the program to decode the file at this address:

             http://math.hws.edu/eck/cs124/labs/lab10/coded.txt
             
        The keyword that was used for encoding this file was

                           javaforever
             
        Before the end of lab, turn in a printout of your modified
        CodedMain.java program.  On the printout, write the answer
        to this question:  When you decoded the file from the Web,
        what sort of stuff did you find in it?

Once you read the assignment, you could modify the CodeMain program as follows. (Changes are shown in blue.)

        /*
           This program demonstrates the use of files, streams, exceptions,
           and the network.  It does this by letting the user encode and
           decode files or send and recieve coded messages over the Internet.
           The routines for sending messages over the Internet are written
           as static routines in the class NetworkCodes.
        */


        import java.io.*;  // Make Java input/output classes available.
        import java.net.*; // Make Java networking classes availalble.

        public class CodeMain {

           static Console console; // A console Window for input/output.
           static boolean done;    // Set to true when user want's to end the program.

           public static void main(String[] args) {
                 // Describe the program to the user, and then use
                 // a while loop to process user commands.
                 
              console = new Console();

              console.putln("This is a demonstration program that works with");
              console.putln("coded messages, streams, files, and network");
              console.putln("communication.  Encoding and decoding of files");
              console.putln("and messages is based on the use of a \"key word.\"");
              console.putln("A file or message can be dcoded by using the same");
              console.putln("key word that was used to encode it.");

              done = false;  // This will be set to true by the menu() routine
                             //    when the user selects the quit command.

              while (!done) {
                 menu();
              }

              console.putln();
              console.putln("OK, quitting...");
              console.close();

           } // end main


           static void menu() {

                // Displays a menu of available operations to the user,
                // reads the user's choice of operation, and carries out
                // the command by calling the appropriate subroutine.
                // If the user's command is "Quit", then the value of 
                // the global variable "done" is set to "true" as a
                // signal to the main() routine that the program should
                // end.

              console.putln();
              console.putln();
              console.putln("What do you want to do?");   // display menu
              console.putln();
              console.putln("        1. Encode a file.");
              console.putln("        2. Decode a file.");
              console.putln("        3. Decode a page from the Internet.");
              console.putln("        4. Send a coded message over the Internet.");
              console.putln("        5. Receive a coded message over the Internet.");
              console.putln("        6. Quit.");
              console.putln();
              console.put("Enter the number of your choice: ");

              int choice = console.getlnInt();   // get user's choice
              console.putln();

              switch (choice) {    // carry out command
                  case 1:
                     doFile(true);
                     break;
                  case 2:
                     doFile(false);
                     break;
                  case 3:
                     doWebPage();
                     break;
                  case 4:
                     NetworkCodedMessage.send(console);
                     break;
                  case 5:
                     NetworkCodedMessage.receive(console);
                     break;
                  case 6:
                     done = true;
                     break;
                  default:
                     console.putln("Illegal input.");
                     break;
              }
         
           }  // end menu()


           static void doFile(boolean encode) {

              // If the parameter encode is "true", this routine will encode
              // a file specified by the user.  If the parameter is "false",
              // it will decode the file.
              //    The encoded or decoded file is stored in another file, whose
              // name is also specified by the user.
              //    The encoding/decoding operation uses a key word, which is
              // specified by the user.  A file that has been encoded with a
              // key word must be decoded with the same keyword.

              DataInputStream in;  // Stream from reading for the source file.
              PrintStream out;     // Stream for writing to the result file.
              Coder coder;         // An object to do the encoding or decoding.
              String inputLine;    // One line input from the file.
              int lineCt = 0;      // Number of lines from the file that have been processed.


              console.put("Name of source file: ");    // Get input file name,
              String inputFileName = console.getln();  //   and create the input stream.
              try {
                 in = new DataInputStream(new FileInputStream(inputFileName));
              }
              catch (IOException e) {
                 console.putln("Can't open file " + inputFileName + ".");
                 console.putln(e.toString());
                 console.putln("Quitting.");
                 return;
              }

              console.put("Name of output file: ");    // Get output file name,
              String outputFileName = console.getln(); //   and create the output stream.
              try {
                 out = new PrintStream(new FileOutputStream(outputFileName));
              }
              catch (IOException e) {
                 console.putln("Can't open file " + outputFileName + ".");
                 console.putln(e.toString());
                 console.putln("Quitting.");
                 return;
              }
              
              console.put("Enter the key word: ");  // Get the keyword and create
              String key = console.getln();         //   the Coder object.
              coder = new Coder(key);

              do {                              // Read a line, encode or decode it,
                 try {                          //   and output the result.
                    inputLine = in.readLine();
                 }
                 catch (IOException e) {
                    console.putln("An error has occured while inputting data.");
                    console.putln(e.toString());
                    break;
                 }
                 if (inputLine != null) {      // A null value indicates end-of-stream.
                    String line;
                    if (encode)
                       line = coder.encode(inputLine);
                    else
                       line = coder.decode(inputLine);
                    out.println(line);
                    lineCt++;
                 }
              } while (inputLine != null);

              if (out.checkError()) {  // Print streams don't throw exceptions.
                                       // Instead, check for errors with checkError();
                 console.putln("Some error has occured while outputting data.");
                 console.putln("Output might not be complete.");
              }

              console.putln(lineCt + " lines processed.");

              try {           // It's good form, though not absolutely necessary,
                 in.close();  //    to close any files that have been opened.
                 out.close();
              }
              catch (IOException e) {
              }

           }  // end of doFile();


           static void doWebPage() {
              // this will read a file from URL on the Web, specified by the
              // user and decode it using a keyword specified by the user.

              DataInputStream in;  // Stream from reading for the source file.
              PrintStream out;     // Stream for writing to the result file.
              Coder coder;         // An object to do the encoding or decoding.
              String inputLine;    // One line input from the file.
              int lineCt = 0;      // Number of lines from the file that have been processed.


              console.put("URL of the coded Web page: ");  // Get URL for page,
              String urlName = console.getln();      //   and create the input stream.
               try {
                 URL url = new URL(urlName);
                 in = new DataInputStream( url.openConnection().getInputStream() );
                 String junk;
                 do {
                   junk = in.readLine();
                 } while (junk != null && !junk.equals(""));
              }
              catch (IOException e) {
                 console.putln("Can't open page " + urlName + ".");
                 console.putln(e.toString());
                 console.putln("Quitting.");
                 return;
              }

              console.put("Name of output file: ");    // Get output file name,
              String outputFileName = console.getln(); //   and create the output stream.
              try {
                 out = new PrintStream(new FileOutputStream(outputFileName));
              }
              catch (IOException e) {
                 console.putln("Can't open file " + outputFileName + ".");
                 console.putln(e.toString());
                 console.putln("Quitting.");
                 return;
              }
              
              console.put("Enter the key word: ");  // Get the keyword and create
              String key = console.getln();         //   the Coder object.
              coder = new Coder(key);

              do {                              // Read a line, encode or decode it,
                 try {                          //   and output the result.
                    inputLine = in.readLine();
                 }
                 catch (IOException e) {
                    console.putln("An error has occured while inputting data.");
                    console.putln(e.toString());
                    break;
                 }
                 if (inputLine != null) {      // A null value indicates end-of-stream.
                    String line = coder.decode(inputLine);
                    out.println(line);
                    lineCt++;
                 }
              } while (inputLine != null);

              if (out.checkError()) {  // Print streams don't throw exceptions.
                                       // Instead, check for errors with checkError();
                 console.putln("Some error has occured while outputting data.");
                 console.putln("Output might not be complete.");
              }

              console.putln(lineCt + " lines processed.");
           
              try {           // It's good form, though not absolutely necessary,
                 in.close();  //    to close any files that have been opened.
                 out.close();
              }
              catch (IOException e) {
              }

           }  // end of doWebPage();

         
        }  // end of class CodeMain


And here is the decoded version of coded.txt that you get when you decode it with the modified program:

        Some quotes from "The Experts Speak," edited by
        Victor Navasky and Christopher Cerf.

        "Where a calculator on the ENIAC is equipped with 18,000 vacuum
        tubes and weighs 30 tons, computers in the future may have only
        1,000 vacuum tubes and weigh 1.5 tons", Popular Mechanics, 1949.

        "It is probable that television drama of high caliber and produced
        by first rate artists will materially raise the level of dramatic
        taste of the  nation", Popular Mechanics, 1939.

        "Nuclear powered vacuum cleaners will be a reality in 10 years",
        a vacuum cleaner manufacturer (quoted in the New York Times), 1955.

        "It is silly talking about how many years we will have to spend in
        the jungles of Vietnam when we could pave the whole country
        and put parking stripes on it and still be home by Christmas",
        Ronald Reagan, 1965.

        "Can't act.  Can't sing.  Balding.  Can dance a little.",
        MGM executive, reviewing Fred Astaire's screen test, 1928.

        "My dynamite will sooner lead to peace than a thousand world
        conventions.  As soon as men will find that in one instant,
        whole armies can be destroyed, they will surely abide by the
        golden peace", Alfred Nobel (inventor of dynamite).

        "A hundred years from now, it is very likely that of Mark Twain's
        works, 'The Jumping Frog' alone will be remembered", The Bookman,
        1901.

David Eck, 12 March 1998