Programming Exercises

   


1:

Implement the necessary exception handling code in Listing 19.1 to prevent the program from stopping abruptly and allow (in a user-friendly manner) the user to assign a value to yourInt in Method2.

Programming exercises 2 4 build on the same program, so please save the program in each exercise.

2:

Write a class called Meteorologist that contains an array named rainfall containing 12 elements (of type int). Write a constructor for the class that assigns an arbitrary number to each of the 12 elements in rainfall. Include a method with the following header in Meteorologist:

 public int GetRainfall(int index) 

This method must return the value of the element in rainfall that corresponds to the given index. Include the necessary code in GetRainfall to handle any out-of-range exceptions thrown from within the GetRainfall method. Implement code to test the Meteorologist class and its method.

3:

During each month, a reading is made for the total amount of pollution absorbed into the rainwater from the air and brought to the ground. Include another array in Meteorologist called pollution, also with 12 elements of type int. Use the constructor from exercise 2 to assign arbitrary values to these 12 elements. Write a method with the header

 public int GetAveragePollution(int index) 

which calculates the average amount of pollution in each unit of rainfall for a given month. For example, to calculate the average pollution in month 4 per rainfall unit, perform the following calculation:

 averagePollution = pollution[3] / rainfall[3] 

Implement the necessary exception handling code for GetAveragePollution. Notice that both an index out-of-range exception as well as a divide by zero exception can be thrown in this method.

4:

The GetAveragePollution method from exercise 3 opens a file on its entry. This file must always be closed before the method exits. Make sure that this is the case. You can pretend the file is being closed with the following line:

 Console.WriteLine("Closing WeatherXYZ file"); 


   


C# Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 286
Authors: Stephen Prata

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net