CS 1401, Quiz #11

Date: Tuesday, April 12, 2005
Name (please type legibly, ideally in block letters): ______________________________________________________________________

1. Exception Handling.  Assume that inFile has been instantiated as a BufferedReader file object variable in the code fragment below.  Read the code fragment and answer questions a), b) and c) at the bottom of the page.  Hint: Recall that the getMessage method is available for exceptions.  It returns the string message supplied as an argument when the exception was thrown.

      int number;

      String newLine;

 

      try
      {             

newLine = inFile.readLine( );
            number  =  Integer.parseInt ( newLine );
            if ( number < 0 ) { 
                 throw new Exception ( “Negative numbers not allowed”); }         
            else  System.out.println ( "Processing data …" );

       }

      catch ( NumberFormatException excep )
       {
            System.out.println ( “Error: Invalid input data” ); 
        }
     

     catch ( Exception excep )
       {
            System.out.println ( "Error: ” + excep.getMessage ( ) ) ;                           
        }


     finally
       {
            inFile.close ( );

System.out.println ( "Finally clause executed" );
        } 
    }     

a)      What is printed as output for the code fragment above if the input from the file is 0

 

b)      What is printed as output for the code fragment above if the input from the file is -1 ?

 

c)      What is printed as output for the code fragment above if the input from the file is 12ab ?

 

2.  File Objects and Looping Statements  

 

A hotel manager would like to know the average number of rooms rented per night for the month of October.  The number of rooms rented for different nights in October is written in a file rooms.txt, with one night per line.  Write a code segment using a while loop that will read in the number of rooms rented for all the nights listed in the file and find the average number of rooms rented per night. Your code should work for a file of any size, and should display a text message stating the average.  For example, if the file contained only 4 lines, representing the number of rooms rented for each of 4 nights, it might appear as follows:

10

9

8

15

The total for all 4 nights is 42 rooms, and the average is 10.5 rooms rented per night (decimals are okay).  The message displayed would be as follows: 

The average number of rooms rented per night in October was 10.5.