CSC 207 Grinnell College Fall, 2014
 
Algorithms and Object-Oriented Design
 

Stream Input in Java

Summary

This laboratory provides practice in reading data from the keyboard and from text files.

Background Reading

Before working on this lab, be sure you have read the reading on stream input in Java.

Acknowledgment

Parts of this lab are edited versions of materials written by Samuel Rebelsky and revised by Jerod Weinman.

Reading Input from a File

  1. Create a testScores package within Eclipse, and import the programs TestScanner1.java, TestScanner2.java, TestScanner3.java, TestBufferedReader1.java, and TestBufferedReader2.java.

    Also copy file /home/walker/public_html/courses/207.sp12/readings/test.data to your account. Then modify the file name in the above programs to reflect your new file name.

  2. Run TestScanner1.java (using your file name), and be sure you can explain how this program works.

    Now try these experiments with TestScanner1.java.

    1. What happens to program execution if you misspell the file or path name?

    2. Delete the try and catch details, so the various steps of reading are completed without a try..catch block. Describe what happens.

    3. Instead of the try..catch syntax, adjust the main method by adding the phrase, throws Exception after the signature. Check that the program now runs successfully. (The point here is that either the possible exception will be handled within main in a try..catch block, or main will send processing outside (in this case to the operating system) if an exception occurs.

    4. Edit your test.data file so that it contains only two test scores instead of three. What happens when you run TestScanner1.java? Briefly explain your answer.

    5. Edit your test.data file so that it contains four test scores instead of three. What happens when you run TestScanner1.java? Briefly explain your answer.

  3. Repeat Step 2 with program TestBufferedReader1.java.

Reading Text from the Keyboard

  1. Today's reading discusses reading input from the keyboard in two ways, using Java's Scanner class and using BufferedReader with InputStreamReader.

    Write a Java program Greet.java 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? Terry
       Have a nice day Terry!
    
    1. Use Java's Scanner class to read this input.
    2. Use BufferedReader with InputStreamReader to read this input.

      In reading a line (using readLine) with a BufferedReader, the operation operation may fail, and the BufferedReader may throw an exception. Thus, either you will need to place the readLine statement within a try..catch block, or you will need to add throws Exception to the declaration of the main method.

      1. Place the readLine within a try..catch block when performing this input.
      2. Specify that main may throw an exception (so no try..catch block will be needed for readLine).

    After you have written a program, you can run it in Eclipse in the usual way. To enter input from the keyboard, type in the "Console" window. Your input will appear in green.

  2. Write a Java program Add.java that reads two [real] numbers from the keyboard and computes (and prints) their sum. (For simplicity, your program may assume that you will enter each number on a separate line.)

    As with Step 1, do this work in two ways, first with the Scanner class and then with a BufferedReader with InputStreamReader.

  3. Modify the previous step, so that the program continues to add your entered numbers until you enter a 0. Once zero is entered, the program should show the total of your numbers.

The Quadratic Formula

  1. Create a class file called QuadraticRoot.java.

    1. QuadraticRoot.java should contain 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.

      For this problem, you should assume that a is not zero.

    2. Write a main method that reads three real numbers from the keyboard, calls smallerQuadraticRoot to determine the root, and prints the result.

  2. Modify smallerQuadraticRoot, so that it tests whether coefficient a is zero. If so, the method should throw an exception.

    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. At the beginning of smallerQuadraticRoot, add a test, 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.");
           }
      
    3. 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.
    4. Modify the main method so that the call to smallerQuadraticRoot is contained in a try..catch block. The program should print an appropriate error message (within main), if the user input yields a non-computable result. For example, part of your main program might include the following:
      try 
      {
        double root = f.smallerQuadraticRoot(a,b,c);
        System.out.println("The smaller root of the polynomial is: " + root);
      }
      catch (Exception e) 
      {
        System.err.println("Sorry, I could not compute a root.");
        System.err.println("Error reported: " + e);
      }
      
    5. Modify the smallerQuadraticRoot method further, so that it throws one type of exception for imaginary roots and another (perhaps a ArithmeticException) if a is zero.

      Then extend the catch clause in main by adding your new ArithmeticException before the catch clause for the generic Exception. For example,

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

Work to Turn In


This document is available on the World Wide Web as

http://www.walker.cs.grinnell.edu/courses/207.sp012/labs/lab-input.shtml

created 7 February 2012
last revised 8 February 2012
Valid HTML 4.01! Valid CSS!
For more information, please contact Henry M. Walker at walker@cs.grinnell.edu.


Copyright © 2011-2014 Henry M. Walker.
CC-BY-NC-SA
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License .