Laboratory: More Java
CSC 207 Algorithms and Object Oriented Design Spring 2011

Summary: In this lab, you will explore the basics of file input and output in Java, as well as dealing with exceptions.

Preparation

  1. Go to your directory from the previous lab.
      cd somewhere/CSC207/labs/intro
  2. Copy the file for this lab to your diretory:
     cp ~weinman/public_html/courses/CSC207/2011S/labs/code/morejava/IntReader.java .
  3. As a point of information, the classes we'll be using in the lab are:

Exercises

Exercise 1

Create a file called Greet.java. In this file, write (and test) a program that prompts the user for a name, reads a name from the keyboard, and prints a greeting to the screen. Your output should resemble the following:
What is your name? Sam
Have a nice day Sam!

For this exercise, use a BufferedReader for input, rather than a Scanner object. You may wish to review Input basics from the reading.

Hint: Be sure your main method includes throws Exception in the declaration, just like First.java from yesterday's lab.

Exercise 2

Recall that a PrintWriter is versatile in its ability to write to the screen or a file.
  1. Write and test a main class called DumpInfo that prints the following three lines to the screen using a PrintWriter object.
    • Your name
    • Your email address
    • Your favorite color
  2. Update DumpInfo so that it instead creates a file and dumps the information to a file.
  3. Predict what will happen when you have DumpInfo.java write to a file that already exists. (For example, if you run it a second time.)
  4. Verify your prediction experimentally.
  5. Predict what will happen when you modify DumpInfo.java to write to a file in a classmate's directory.
  6. Verify your prediction experimentally.

Exercise 3

  1. Write and test a main class called ShowInfo that reads a file of three lines named info and prints each line preceeded by a category (Name, Email, Color). For example, if the file contains
    J. Doe
    doej@gmail.com
    plaid
              

    the output on the screen should be

    Name: J. Doe
    Email: doej@gmail.com
    Fave Color: plaid
              
  2. Modify info and verify that ShowInfo continues to work correctly.

Exercise 4

  1. What do you expect to happen when you run ShowInfo if info contains only two lines (e.g., doesn't contain a color)?
  2. Verify your answer experimentally.
  3. What do you expect to happen when you run ShowInfo if info does not exist?
  4. Verify your answer experimentally.
  5. What do you expect to happen when you run ShowInfo using a file in a classmate's directory?
  6. Verify your answer experimentally.

Exercise 5

The class IntReader, which you copied in the preparations for this lab, has a method, readInt, that reads an integer, and maintests that method.
  1. Remove the throws Exception from the main method and determine what, if any, error messages you get. If it compiles, try running the program.

    After you finish exploring the effects of that removal, reinsert the throws warning.

  2. Remove the throws Exception from the definition of readInt and determine what, if any, error messages you get. If it compiles, try running the program with that warning removed.

    Do not reinsert the warning.

  3. Within the readInt method, enclose the two lines in a try/catch clause that returns 0 if an exception is thrown, as in
    try 
    {
      String str = br.readLine();
      return Integer.parseInt(str);
    }
    catch (Exception e) 
    {
      return 0;
    }

    Compile to verify that Java is no longer concerned about any errors in your code.

  4. Determine what happens when the user enters an invalid value (such as Hello) in response to a request for an integer.

For Those with Extra Time

Exercise 6

  1. Create a class file called QuadraticRoot.java.
  2. Write a method
    public static double smallQuadraticRoot(double a, double b, double c)
    that computes the smaller of the two roots of a quadratic.

    Note that you can use the following formula to compute that root:

    (-b - sqrt(b2 - 4ac))/2a

    You will, of course, have to translate that mathematical expression into Java code.

  3. Write a method testQR that computes the roots for a variety of quadratics. Note that it is easiest if you choose quadratics for which you know the solution. For example,
    • If we multiply x-2 and x+5, we get x2+3-10, we know the roots are 2 and -5.
    • If we multiply 2x+3 and 3x-4, giving us 6x2+x-12, we know that the roots are -3/2 and 4/3.
  4. Extend your code to verify that each result is, in fact, a root of the corresponding function. That is, you should confirm that a*root*root + b*root + c is about 0.

Exercise 7

  1. Add a main routine that accepts three command-line arguments, the coefficients of a quadratic function, then prints the smaller root of the quadratic and the value of the quadratic at that root.

    Note: You may want to know about the Double.parseDouble method.

  2. Determine what happens if the user enters 0 for the coefficient of x2.
  3. Determine what happens if user enters values for which there is no real root.
  4. Determine what happens if the user enters values for which the function has only one root (e.g., x2-2x+1 has only one root)?

Exercise 8

  1. Extend smallerQuadraticRoot to indicate that it may throw an exception. Note that you'll need to change the method head for smallerQuadraticRoot to something like the following
      public static double smallerQuadraticRoot(double a, double b, double c)
        throws Exception
  2. Can you successfully compile your modified code? If not, make any changes necessary to permit you to compile it.
  3. What now happens if you enter the erroneous input described in the previous exercise?

Exercise 9

  1. Extend smallerQuadraticRoot so that it throws an exception if a is 0. For example,
    if (a == 0)
    {
      throw new Exception("Cannot compute quadratic roots of linear functions.");
    }
  2. Extend smallerQuadraticRoot so that it throws an exception if the root is not real (i.e., if it has an imaginary component). Note that the root is not real if the thing you're taking a square root of is negative.
  3. What now happens if you enter the erroneous input described above?

Exercise 10

  1. If you've written your main method using the template presented earlier, you have the line throws Exception in the head of that method. Remove that line.
  2. What effect do you expect removing that line will have?
  3. Verify your answer experimentally. Ask a neighbor or the instructor if you don't understand the results of your experiment.
  4. Enclose your call to smallerQuadraticRoot in a try/catch block. For example,
    try 
    {
      double root = f.smallerQuadraticRoot(a,b,c);
      System.out.println("The smaller root of the polynomial is: " + root);
      System.out.println("Experimentally, " + a + "*" + root + "*" + root +
                         "+" + b + "*>" + root + "+" + c + " = " +
                         (a*root*root + b*root + c));
    }
    catch (Exception e) 
    {
      System.err.println("Sorry, I could not compute a root.");
    }
  5. Determine what happens with the problematic inputs described above.

Exercise 11

a. Update smallerQuadraticRoot so that it tries to throw a DivideByZeroException if the coefficient of the quadratic term is 0. You can still throw a generic exception if the result includes an imaginary component.

b. What do you expect to happen when you try to compile the revised program?

c. Verify your answer experimentally.

Exercise 12

As you should have determined in the previous exercise, Java does not know by default what a DivideByZeroException is. Hence, you'll need to create your own Exception. You can do so using the template for user-defined exceptions.

a. Create and compile a Java file for DivideByZeroException. That is, begin with the template, replace the package name by your current package name, replace YourException by DivideByZeroException, and fill in the default message.

b. Verify that the previously-modified code now works.

Exercise 13

a. Extend your code that it has a catch clause for your new DivideByZeroException before the catch clause for the generic Exception. For example,

try 
{
  ...
}
catch (DivideByZeroException dbze) 
{
  System.err.println("Cannot compute a result because the coefficient of the quadratic term is 0.");
}
catch (Exception e)
{
  ...
}

b. Determine what happens in each of the problematic cases.

c. What do your results for this problem suggest?

Created: Samuel A. Rebelsky, 31 January 2005
Modified: Jerod Weinman, 26 January 2011
Adopted from Espresso: Laboratory: Simple Input and Output, and Espresso: Laboratory: Exceptions