Lecture 27 Log into Windows/ACENET. Start MS VS and open the PointClassDemo project. Reminder: Project 1 is due on Wednesday. Questions? Monday, March 21 CS 205 Programming for the Sciences - Lecture 27 1 Outline Classes – Chapter 4 Instance methods Static methods Properties Exceptions and exception handling Monday, March 21 CS 205 Programming for the Sciences - Lecture 27 2 Static Methods The methods we wrote for our console programs used the static modifier. This is used when the method is to be called without a class object. Since it is defined in a class, it is called with the class name. E.g., Math.Sqrt( ) One important static method is Parse( ), which is used when a user is expected to enter values of the class from the keyboard. For example, we have used double.Parse( ) and int.Parse( ) to interpret user input strings into double and int values, respectively. Monday, March 21 CS 205 Programming for the Sciences - Lecture 27 3 Parse( ) Method A Parse( ) method basically ignores any punctuation in the user entered string and converts the rest into attribute values. For the Point class, we want to parse strings of the form "(x,y)", where x and y are numbers. This involves find the substrings between the punctuation and convert them into the coordinate values and construct a Point object with them. Monday, March 21 CS 205 Programming for the Sciences - Lecture 27 4 Parse( ) Method For example, for (12.5,-3.14) find these substrings and convert to numbers for x and y Two string methods are useful for doing this FindIndexOf( ) receives a character to search for and returns the index of the first occurrence of the character if it is present, or -1 if it is not. Substring( ) receives the starting index of a substring and the number of characters in the substring. It returns a (new) substring consisting of the character at the starting index and the next number of characters or to the end of the string, whichever is reached first. Monday, March 21 CS 205 Programming for the Sciences - Lecture 27 5 Parse( ) Method For now, we will assume that the user enters a well-formed string, i.e., '(' is the first character, ')' is the last character, and there is a ',' in the middle of the string between two substrings that are valid numbers. Here is the basic algorithm: Find the index of the ',' using FindIndexOf( ) Compute the start index and length of the two substrings Use Substring( ) to get the substrings Use double.Parse( ) to convert them into numbers Create and return a Point with these coordinates Monday, March 21 CS 205 Programming for the Sciences - Lecture 27 6 Parse( ) Method static Point Parse (string input) { int commaIndex = input.FindIndexOf(','); int xStartIndex = 1; int xLength = commaIndex – 1; int yStartIndex = commaIndex + 1; int yLength = input.Length – commaIndex – 2; string xString = input.Substring(xStartIndex, xLength); string yString = input.Substring(yStartIndex, yLength); double newX = double.Parse(xString); double newY = double.Parse(yString); return new Point(newX, newY); // create a Point } Monday, March 21 CS 205 Programming for the Sciences - Lecture 27 7 Testing Parse( ) To test the Parse( ) methods, we will write handlers for the Enter buttons. Double-click on the left Enter button to go to the button handler this button. This handler does the following: Use Point.Parse( ) to parse txtPoint1.Text and assign the result to variable p1 Set the Text property of lblPoint1 to p1.ToString( ) Clear txtPoint1.Text Add an item to lbxResults.Items indicating the result of the handler (this is already completed) Monday, March 21 CS 205 Programming for the Sciences - Lecture 27 8 Testing Parse( ) private void btnEnterP1_Click(object sender, EventArgs e) { p1 = Point.Parse(txtPoint1.Text); lblPoint1.Text = p1.ToString(); txtPoint1.Text = ""; lbxResults.Items.Add ("Entered p1: " + p1.ToString()); } Monday, March 21 CS 205 Programming for the Sciences - Lecture 27 9 Testing Parse( ) Build and run your program. You should be able to input a Point in "(x,y)" form in the left textbox, click on the left Enter button, and see the label above the textbox change to the input and the textbox become empty, along with a message in the results area. Repeat these steps for right Enter button handler. This handler is exactly the same, except that is uses p2, txtPoint2, and lblPoint2. Monday, March 21 CS 205 Programming for the Sciences - Lecture 27 10 Magnitude( ) Method The magnitude of a Point (x,y) is its distance from the origin (0,0) computed using the formula: distance= x y 2 2 The Point class instance method Magnitude( ) returns the magnitude its Point object. Write the method definition for Magnitude in the file Point.cs. Monday, March 21 CS 205 Programming for the Sciences - Lecture 27 11 Testing Magnitude( ) Double-click on the Magnitude button to get a stub for its handler. Write code to compute the magnitude of Points p1 and p2, and display these results in the results area ListBox. Monday, March 21 CS 205 Programming for the Sciences - Lecture 27 12 Getters and Setters As noted last time, we make the attributes private so that the class can control access to them, preventing applications from creating invalid objects. However, often an application would like to read or change an attribute. To support such actions a class can provide a getter method that returns the attribute and a setter method that receives and assigns a new value to the attribute. Monday, March 21 CS 205 Programming for the Sciences - Lecture 27 13 Getters and Setters E.g., to allow an application to get and set the x-coordinate of a Point, we could write instance methods: // Getter double GetX () { return x; } // Setter void SetX(double newX) { x = newX; } Monday, March 21 CS 205 Programming for the Sciences - Lecture 27 14 Getters and Setters To use these methods, we call them as usual. E.g. for Point object p1: // In btnGetX_Click lbxResults.Items.Add("p1's x­coordinate is: " + p1.GetX().ToString()); // In btnSetX_Click // Get new coordinate from input textbox, if exists if (txtPoint1.Text != "") { double newX = double.Parse(txtInput.Text); p1.SetX(newX); txtPoint1.Text = ""; lblPoint1 = p1.ToString(); } Monday, March 21 CS 205 Programming for the Sciences - Lecture 27 15 Properties While getter and setter methods work, they are tedious write and use, especially needing to type the ( )'s everywhere. It would be more convenient for the application programmer if the syntax for this use could be as if the attribute were a public data member. E.g., for the Point class, we might like to be able to write: lbxResults.Items.Add("p1's x­coordinate is: " + p1.X) p1.X = newX; Monday, March 21 CS 205 Programming for the Sciences - Lecture 27 16 Properties C# has a special method definition that allows us to define getters and setters that are called using this syntax called a property. By convention, a property's name is the same as the attribute it accesses only capitalized. (This assumes the convention that the attribute variables start with a lowercase letter.) E.g., Point attribute x is accessed using property X. Monday, March 21 CS 205 Programming for the Sciences - Lecture 27 17 Properties The getter and setter for a property are defined together. Either is optional. (E.g., you might want to allow applications to read an attribute, but not change it.) public double X // name of property { get // getter definition { return x; } set // setter definition { x = value; // value is an implicit argument } // from right side of assignment } Monday, March 21 CS 205 Programming for the Sciences - Lecture 27 18 Properties Write a property with getters and setters for the y-coordinate attribute in Point.cs. Properties are accessed as shown previously. In particular, there are no ( )'s to call them. Monday, March 21 CS 205 Programming for the Sciences - Lecture 27 19 Properties Complete the GetX, GetY, SetX, and SetY button handlers for PointClassDemo.cs. GetX is to display the x-coordinate of Point objects p1 and p2 in the results area using the X property GetY is to do the same for the y-coordinates of each point. SetX is to convert the input strings in each textbox (if they are not empty strings) into double values and set the x-coordinate using the X property for each point. SetY is to do the same for the ycoordinates of each point. Monday, March 21 CS 205 Programming for the Sciences - Lecture 27 20 Exception Handling So far we have ignored what happens when a user types in input that is ill-formed. In the absence of any error handling, a program usually will abort with an unhandled exception. An exception is an object that is thrown by a method when an error occurs. To handle an exception, it is caught by the code that called the method. For GUI programs, the usual action is to inform the user and go back to waiting for input. Monday, March 21 CS 205 Programming for the Sciences - Lecture 27 21 Exception Handling When an exception is thrown, if the calling method does not catch it, the caller is immediately aborted and the exception is rethrown. For example, most Parse( ) methods will throw a FormatException if the string being parsed is not well-formed. In the Point.Parse( ) method, we call double.Parse( ), but we can ignore any exceptions that it throws and they will be passed on to Point.Parse( )'s caller. Monday, March 21 CS 205 Programming for the Sciences - Lecture 27 22 Exception Handling unhandled exception dialog incorrect input name of exception under "Details"; also a backtrace of calls Monday, March 21 CS 205 Programming for the Sciences - Lecture 27 23 Exception Handling Sometimes a caller wants to do something when an error occurs, such as inform the user that an error has happened and tell them what to do. For example, in the handlers for the Enter, SetX, and SetY buttons we would like to inform the user of the error via a MessageBox and then go back to waiting for user input. Monday, March 21 CS 205 Programming for the Sciences - Lecture 27 24 Try-Catch Statement Exceptions are handled by putting calls in a trycatch statement. This statement has the following syntax: try { // method calls that may throw an exception // there may be more than one such call } catch (<exception type> ex) { // do something about the error } // more than one catch block can be attached // the first one that matches is executed Monday, March 21 CS 205 Programming for the Sciences - Lecture 27 25 Try-Catch Statement In btnEnterP1_Click, we can catch any FormatExceptions as follows: try { p1 = Point.Parse(txtPoint1.Text); } catch (FormatException ex) { MessageBox.Show ("Input is invalid. Must be (#,#).", "Point Class Demo"); txtPoint1.Text = ""; // clear textbox return; // go back to waiting } // rest of handler goes here Monday, March 21 CS 205 Programming for the Sciences - Lecture 27 26 Exception Handling incorrect input MessageBox shown when FormatException is thrown Monday, March 21 CS 205 Programming for the Sciences - Lecture 27 27 Throwing Exceptions Our Point.Parse( ) method now throws a FormatException when the numeric portions of the input are incorrect. But there are other possible input errors: The first character must be '(' and the last character must be ')'. Currently, any character can be in those places. There must be a ',' in the middle. If not, the code that computes the two number substrings will be incorrect. Monday, March 21 CS 205 Programming for the Sciences - Lecture 27 28 Throwing Exceptions incorrect input the second substring has computed length < 0, which is not allowed Monday, March 21 CS 205 Programming for the Sciences - Lecture 27 29 Throwing Exceptions The exception thrown by the Substring method is not meaningful to Point.Parse( ) callers. We want a FormatException thrown instead. To throw an exception, we use the throw operator with a new exception object as shown: int commaIndex = input.FindIndexOf(','); if ((input[0] != '(') || (input[input.Length ­ 1] != ')') || (commaIndex == ­1)) throw new FormatException("Invalid Point"); // rest of Parse method code goes here Monday, March 21 CS 205 Programming for the Sciences - Lecture 27 30