Wrap-Up

Answers to Self Review Exercises

9.1

a) Format. b) hides. c) destructor. d) default constructor. e) ToString. f) has-a. g) static. h) principle of least privilege. i) const, readonly. j) abstract data type (ADT). k) reference. l) dynamic link library. m) public services, public interface. n) Collect. o) consistent data.

Exercises

9.2

Explain the notion of internal access in C#.

9.3

What happens when a return type, even void, is specified for a constructor?

9.4

(Rectangle Class) Create class Rectangle. The class has attributes length and width, each of which defaults to 1. It has read-only properties that calculate the Perimeter and the Area of the rectangle. It has properties for both length and width. The set accessors should verify that length and width are each floating-point numbers greater than 0.0 and less than 20.0. Write an application to test class Rectangle.

9.5

(Modifying the Internal Data Representation of a Class) It would be perfectly reasonable for the Time2 class of Fig. 9.7 to represent the time internally as the number of seconds since midnight rather than the three integer values hour, minute and second. Clients could use the same public methods and properties to get the same results. Modify the Time2 class of Fig. 9.7 to implement the Time2 as the number of seconds since midnight and show that no change is visible to the clients of the class by using the same test application from Fig. 9.8.

9.6

(Savings Account Class) Create class SavingsAccount. Use static variable annualInterestRate to store the annual interest rate for all account holders. Each object of the class contains a private instance variable savingsBalance, indicating the amount the saver currently has on deposit. Provide method CalculateMonthlyInterest to calculate the monthly interest by multiplying the savingsBalance by annualInterestRate divided by 12this interest should be added to savingsBalance. Provide static method ModifyInterestRate to set the annualInterestRate to a new value. Write an application to test class SavingsAccount. Create two savingsAccount objects, saver1 and saver2, with balances of $2000.00 and $3000.00, respectively. Set annualInterestRate to 4%, then calculate the monthly interest and print the new balances for both savers. Then set the annualInterestRate to 5%, calculate the next month's interest and print the new balances for both savers.

9.7

(Enhancing Class Time2) Modify class Time2 of Fig. 9.7 to include a Tick method that increments the time stored in a Time2 object by one second. Provide method IncrementMinute to increment the minute and method IncrementHour to increment the hour. The Time2 object should always remain in a consistent state. Write an application that tests the Tick method, the IncrementMinute method and the IncrementHour method to ensure that they work correctly. Be sure to test the following cases:

  1. incrementing to the next minute,
  2. incrementing to the next hour and
  3. incrementing to the next day (i.e., 11:59:59 PM to 12:00:00 AM).
9.8

(Enhancing Class Date) Modify class Date of Fig. 9.9 to perform error checking on the initializer values for instance variables month, day and year (class Date currently validates only the month and day). Provide method Nextday to increment the day by 1. The Date object should always remain in a consistent state. Write an application that tests the NexTDay method in a loop that prints the date during each iteration of the loop to illustrate that the Nextday method works correctly. Test the following cases:

  1. incrementing to the next month and
  2. incrementing to the next year.
9.9

(Complex Numbers) Create a class called Complex for performing arithmetic with complex numbers. Complex numbers have the form

realPart + imaginaryPart * i
 

where i is

Write an application to test your class. Use floating-point variables to represent the private data of the class. Provide a constructor that enables an object of this class to be initialized when it is declared. Provide a parameterless constructor with default values in case no initializers are provided. Provide public methods that perform the following operations:

  1. Add two Complex numbers: The real parts are added together and the imaginary parts are added together.
  2. Subtract two Complex numbers: The real part of the right operand is subtracted from the real part of the left operand, and the imaginary part of the right operand is subtracted from the imaginary part of the left operand.
  3. Return a string representation of a Complex number in the form (a, b), where a is the real part and b is the imaginary part.
9.10

(Date and Time Class) Create class DateAndTime that combines the modified Time2 class of Exercise 9.7 and the modified Date class of Exercise 9.8. Modify method IncrementHour to call method NexTDay if the time is incremented to the next day. Modify methods ToString and ToUniversalString to output the date and time. Write an application to test the new class DateAndTime. Specifically, test incrementing the time to the next day.

9.11

(Enhanced Rectangle Class) Create a more sophisticated Rectangle class than the one you created in Exercise 9.4. This class stores only the Cartesian coordinates of the four corners of the rectangle. The constructor calls a SetCoordinates method that accepts four sets of coordinates and verifies that each of these is in the first quadrant with no single x- or y-coordinate larger than 20.0. The method also verifies that the supplied coordinates specify a rectangle. Provide read-only properties that get the Length, Width, Perimeter and Areabut do not store these values in instance variables. Write get accessors that calculate and return these values. The length is the larger of the two dimensions. Include methods IsRectangle and IsSquare that determine whether this is a rectangle and square, respectively. Write an application to test class Rectangle.

9.12

(Set of Integers) Create class IntegerSet. Each IntegerSet object can hold integers in the range 0100. The set is represented by an array of bools. Array element a[i] is TRue if integer i is in the set. Array element a[j] is false if integer j is not in the set. The parameterless constructor initializes the array to the "empty set" (i.e., a set whose array representation contains all false values).

Provide the following methods:

  1. Method Union creates a third set that is the set-theoretic union of two existing sets (i.e., an element of the third set's array is set to true if that element is true in either or both of the existing setsotherwise, the element of the third set is set to false).
  2. Method Intersection creates a third set which is the set-theoretic intersection of two existing sets (i.e., an element of the third set's array is set to false if that element is false in either or both of the existing setsotherwise, the element of the third set is set to true).
  3. Method InsertElement inserts a new integer k into a set (by setting a[k] to true).
  4. Method DeleteElement deletes integer m (by setting a[m] to false).
  5. Method ToString returns a string containing a set as a list of numbers separated by spaces. Include only those elements that are present in the set. Use --- to represent an empty set.
  6. Method IsEqualTo determines whether two sets are equal.

Write an application to test class IntegerSet. Instantiate several IntegerSet objects. Test that all your methods work properly.

9.13

(Date Class) Create class Date with the following capabilities:

  1. Output the date in multiple formats, such as

    MM/DD/YYYY
    June 14, 1992
    DDD YYYY
    
  2. Use overloaded constructors to create Date objects initialized with dates of the formats in part (a). In the first case, the constructor should receive three integer values. In the second case, it should receive a string and two integer values. In the third case it should receive two integer values, the first of which represents the day number in the year. [Hint: To convert the string representation of the month to a numeric value, declare a string array of month names in order and iterate through the array, comparing the string to each element. Use the index of the matching month name to calculate the month's numeric value.]
9.14

(Rational Numbers) Create a class called Rational for performing arithmetic with fractions. Write an application to test your class. Use integer variables to represent the private instance variables of the classthe numerator and the denominator. Provide a constructor that enables an object of this class to be initialized when it is declared. The constructor should store the fraction in reduced form. The fraction

2/4
 

is equivalent to 1/2 and would be stored in the object as 1 in the numerator and 2 in the denominator. Provide a parameterless constructor with default values in case no initializers are provided. Provide public methods that perform each of the following operations (all calculation results should be stored in a reduced form):

  1. Add two Rational numbers.
  2. Subtract two Rational numbers.
  3. Multiply two Rational numbers.
  4. Divide two Rational numbers.
  5. Print Rational numbers in the form a/b, where a is the numerator and b is the denominator.
  6. Print Rational numbers in floating-point format. (Consider providing formatting capabilities that enable the user of the class to specify the number of digits of precision to the right of the decimal point.)
9.15

(Huge Integer Class) Create a class HugeInteger which uses a 40-element array of digits to store integers as large as 40 digits each. Provide methods Input, ToString, Add and Subtract. For comparing HugeInteger objects, provide the following methods: IsEqualTo, IsNotEqualTo, IsGreaterThan, IsLessThan, IsGreaterThanOrEqualTo and IsLessThanOrEqualTo. Each of these is a method that returns true if the relationship holds between the two HugeInteger objects and returns false if the relationship does not hold. Provide method IsZero. If you feel ambitious, also provide methods Multiply, Divide and Remainder.

9.16

(Tic-Tac-Toe) Create class TicTacToe that will enable you to write a complete application to play the game of Tic-Tac-Toe. The class contains a private 3-by-3 rectangular array of integers. The constructor should initialize the empty board to all 0s. Allow two human players. Wherever the first player moves, place a 1 in the specified square, and place a 2 wherever the second player moves. Each move must be to an empty square. After each move, determine whether the game has been won and whether it is a draw. If you feel ambitious, modify your application so that the computer makes the moves for one of the players. Also, allow the player to specify whether he or she wants to go first or second. If you feel exceptionally ambitious, develop an application that will play threedimensional Tic-Tac-Toe on a 4-by-4-by-4 board.


Preface

Index

    Introduction to Computers, the Internet and Visual C#

    Introduction to the Visual C# 2005 Express Edition IDE

    Introduction to C# Applications

    Introduction to Classes and Objects

    Control Statements: Part 1

    Control Statements: Part 2

    Methods: A Deeper Look

    Arrays

    Classes and Objects: A Deeper Look

    Object-Oriented Programming: Inheritance

    Polymorphism, Interfaces & Operator Overloading

    Exception Handling

    Graphical User Interface Concepts: Part 1

    Graphical User Interface Concepts: Part 2

    Multithreading

    Strings, Characters and Regular Expressions

    Graphics and Multimedia

    Files and Streams

    Extensible Markup Language (XML)

    Database, SQL and ADO.NET

    ASP.NET 2.0, Web Forms and Web Controls

    Web Services

    Networking: Streams-Based Sockets and Datagrams

    Searching and Sorting

    Data Structures

    Generics

    Collections

    Appendix A. Operator Precedence Chart

    Appendix B. Number Systems

    Appendix C. Using the Visual Studio 2005 Debugger

    Appendix D. ASCII Character Set

    Appendix E. Unicode®

    Appendix F. Introduction to XHTML: Part 1

    Appendix G. Introduction to XHTML: Part 2

    Appendix H. HTML/XHTML Special Characters

    Appendix I. HTML/XHTML Colors

    Appendix J. ATM Case Study Code

    Appendix K. UML 2: Additional Diagram Types

    Appendix L. Simple Types

    Index



    Visual C# How to Program
    Visual C# 2005 How to Program (2nd Edition)
    ISBN: 0131525239
    EAN: 2147483647
    Year: 2004
    Pages: 600

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