Presentation is loading. Please wait.

Presentation is loading. Please wait.

Microsoft Visual C#.NET: From Problem Analysis to Program Design1 Chapter 4 Methods and Behaviors Microsoft Visual C#.NET: From Problem Analysis to Program.

Similar presentations


Presentation on theme: "Microsoft Visual C#.NET: From Problem Analysis to Program Design1 Chapter 4 Methods and Behaviors Microsoft Visual C#.NET: From Problem Analysis to Program."— Presentation transcript:

1 Microsoft Visual C#.NET: From Problem Analysis to Program Design1 Chapter 4 Methods and Behaviors Microsoft Visual C#.NET: From Problem Analysis to Program Design

2 2 Chapter Objectives Become familiar with the components of a method Call class methods with and without parameters Use predefined methods in the Console and Math classes Write your own value and non-value returning class methods (with and without parameters) Learn about the different methods and properties used for object-oriented development

3 Microsoft Visual C#.NET: From Problem Analysis to Program Design3 Chapter Objectives ( continued ) Write your own instance methods to include constructors, mutators, and accessors Call instance methods including constructors, mutators, and accessors Distinguish between value, ref, and out parameter types Work through a programming example that illustrates the chapter’s concepts

4 Microsoft Visual C#.NET: From Problem Analysis to Program Design4 Anatomy of a Method Methods defined inside classes Group program statements –Based on functionality –Called one or more times All programs consist of at least one method –Main( ) User-defined method

5 Microsoft Visual C#.NET: From Problem Analysis to Program Design5 /* SquareExample.csAuthor:Doyle*/ using System; namespace Square { public class SquareExample { public static void Main( ) { int aValue = 768; int result; result = aValue * aValue; Console.WriteLine(“{0} squared is {1}”, aValue, result); Console.Read( ); } Required method

6 Microsoft Visual C#.NET: From Problem Analysis to Program Design6 Anatomy of a Method ( continued )

7 Microsoft Visual C#.NET: From Problem Analysis to Program Design7 Modifiers Appear in method headings Appear in the declaration heading for classes and other class members Indicates how it can be accessed Types of modifiers –static –Access

8 Microsoft Visual C#.NET: From Problem Analysis to Program Design8 Static Modifier Indicates member belongs to the type itself rather than to a specific object of a class Main( ) must include static in heading Members of the Math class are static public static double Pow(double, double) Methods that use the static modifier are called class methods –Instance methods require an object

9 Microsoft Visual C#.NET: From Problem Analysis to Program Design9 Access Modifiers public protected internal protected internal private

10 Microsoft Visual C#.NET: From Problem Analysis to Program Design10 Level of Accessibility

11 Microsoft Visual C#.NET: From Problem Analysis to Program Design11 Return Type Indicates what type of value is returned when the method is completed Always listed immediately before method name void –No value being returned return statement –Required for all non-void methods –Compatible value

12 Microsoft Visual C#.NET: From Problem Analysis to Program Design12 Return Type ( continued ) public static double CalculateMilesPerGallon (int milesTraveled, double gallonsUsed) { return milesTraveled / gallonsUsed; } Compatible value (double) returned Return type

13 Microsoft Visual C#.NET: From Problem Analysis to Program Design13 Method Names Follow the rules for creating an identifier –Pascal case style –Action verb or prepositional phrase Examples –CalculateSalesTax( ) –AssignSectionNumber( ) –DisplayResults( ) –InputAge( ) –ConvertInputValue( )

14 Microsoft Visual C#.NET: From Problem Analysis to Program Design14 Parameters Supply unique data to method Appear inside parentheses –Include data type and an identifier In method body, reference values using identifier name –Parameter refers to items appearing in the heading –Argument for items appearing in the call Formal parameters Actual arguments

15 Microsoft Visual C#.NET: From Problem Analysis to Program Design15 Parameters ( continued ) public static double CalculateMilesPerGallon (int milesTraveled, double gallonsUsed) { return milesTraveled / gallonsUsed; } Call to method inside Main( ) method Console.WriteLine(“Miles per gallon = {0:N2}”, CalculateMilesPerGallon(289, 12.2)); Two formal parameters Actual arguments

16 Microsoft Visual C#.NET: From Problem Analysis to Program Design16 Parameters ( continued ) Like return types, parameters are optional –Keyword void not required – when there are no parameters public void DisplayMessage( ) { Console.Write(”This is “); Console.Write(”an example of a method ”); Console.WriteLine(“body. ”); return; // no value is returned }

17 Microsoft Visual C#.NET: From Problem Analysis to Program Design17 Method Body Enclosed in curly braces Include statements ending in semicolons –Declare variables –Do arithmetic –Call other methods Value returning methods must include return statement

18 Microsoft Visual C#.NET: From Problem Analysis to Program Design18 Calling Class Methods Invoke a method Call to method that returns no value [qualifier].MethodName(argumentList); Qualifier –Square brackets indicates optional –class or object name Call to method does not includes data type Use Intellisense

19 Microsoft Visual C#.NET: From Problem Analysis to Program Design19 Predefined Methods Extensive class library Console class –Overloaded methods –Write( ) –WriteLine( ) –Read( ) No overloaded Returns an integer

20 Microsoft Visual C#.NET: From Problem Analysis to Program Design20 Intellisense 3-D fuchsia colored box—methods aqua colored box—fields ( not shown ) Method signature(s) and description After typing the dot, list of members pops up

21 Microsoft Visual C#.NET: From Problem Analysis to Program Design21 Intellisense Display Figure 4-3 string argument expected string parameter 18 different Write( ) methods

22 Microsoft Visual C#.NET: From Problem Analysis to Program Design22 Intellisense Display ( continued )

23 Microsoft Visual C#.NET: From Problem Analysis to Program Design23 Call Read( ) Methods int aNumber; Console.Write(“Enter a single character: ”); aNumber = Console.Read( ); Console.WriteLine(“The value of the character entered: ” + aNumber); Enter a single character: a The value of the character entered: 97

24 Microsoft Visual C#.NET: From Problem Analysis to Program Design24 Call Read( ) Methods ( continued ) int aNumber; Console.WriteLine(“The value of the character entered: “ + (char) Console.Read( )); Enter a single character: a The value of the character entered: a

25 Microsoft Visual C#.NET: From Problem Analysis to Program Design25 Call ReadLine( ) Methods More versatile that the Read( ) Returns all characters up to the enter key Not overloaded Always returns a string String value must be parsed

26 Microsoft Visual C#.NET: From Problem Analysis to Program Design26 Call Parse( ) Predefined static method All numeric types have a Parse( ) method –double.Parse(“string number”) –int.Parse(“string number”) –char.Parse(“string number”) –Bool.Parse(“string number”) Expects string argument –Argument must be a number—string format Returns the number (or char or bool)

27 Microsoft Visual C#.NET: From Problem Analysis to Program Design27 /* AgeIncrementer.csAuthor:Doyle */ using System; namespace AgeExample { public class AgeIncrementer { public static void Main( ) { int age; string aValue; Console.Write(“Enter your age: “); aValue = Console.ReadLine( ); age = int.Parse(aValue); Console.WriteLine(“Your age next year” + “ will be {0}”, ++age); Console.Read( ); } } }

28 Microsoft Visual C#.NET: From Problem Analysis to Program Design28 /* SquareInputValue.csAuthor: Doyle */ using System; namespace Square { class SquareInputValue { static void Main( ) { string inputStringValue; double aValue, result; Console.Write(“Enter a value to be squared: ”); inputStringValue = Console.ReadLine( ); aValue = double.Parse(inputStringValue); result = Math.Pow(aValue, 2); Console.WriteLine(“{0} squared is {1}”, aValue, result); } } }

29 Microsoft Visual C#.NET: From Problem Analysis to Program Design29 Call Parse( ) ( continued ) string sValue = “True”; Console.WriteLine (bool.Parse(sValue)); // displays True string strValue = “q”; Console.WriteLine(char.Parse(strValue)); // displays q

30 Microsoft Visual C#.NET: From Problem Analysis to Program Design30 Call Parse( ) with Incompatible Value Console.WriteLine(char.Parse(sValue)); when sValue referenced “True”

31 Microsoft Visual C#.NET: From Problem Analysis to Program Design31 Convert Class More than one way to convert from one base type to another –System namespace—Convert class—static methods –Convert.ToDouble( ) –Convert.ToDecimal( ) –Convert.ToInt32( ) –Convert.ToBoolean( ) –Convert.ToChar( ) int newValue = Convert.ToInt32(stringValue);

32 Microsoft Visual C#.NET: From Problem Analysis to Program Design32 Math Class

33 Microsoft Visual C#.NET: From Problem Analysis to Program Design33 Math Class ( continued )

34 Microsoft Visual C#.NET: From Problem Analysis to Program Design34 Math Class ( continued )

35 Microsoft Visual C#.NET: From Problem Analysis to Program Design35 Math( ) Class double aValue = 78.926; double result1, result2; result1 = Math.Floor(aValue); // result1 = 78 result2 = Math.Sqrt(aValue); // result2 = 8.88403061678651 Console.Write(“aValue rounded to 2 decimal places” + “ is {0}”, Math.Round(aValue, 2)); aValue rounded to 2 decimal places is 78.93 Each call returns a value

36 Microsoft Visual C#.NET: From Problem Analysis to Program Design36 Method Calls That Return Values Line 1 int aValue = 200; Line 2 int bValue = 896; Line 3 int result; Line 4 result = Math.Max(aValue, bValue); // result = 896 Line 5 result += bValue * Line 6 Math.Max(aValue, bValue) – aValue; // result = 896 + (896 * 896 - 200) (result = 803512) Line 7 Console.WriteLine(“Largest value between {0} ” Line 8 + “and {1} is {2}”, aValue, bValue, Line 9 Math.Max(aValue, bValue)); In an assignment statement Part of arithmetic expression Argument to another method call

37 Microsoft Visual C#.NET: From Problem Analysis to Program Design37 Writing Your Own Class Methods [modifier(s)] returnType MethodName ( parameterList ) { // body of method - consisting of executable statements } void Methods –Simplest to write –No return statement

38 Microsoft Visual C#.NET: From Problem Analysis to Program Design38 Writing Your Own Class Methods – void Types public static void DisplayInstructions( ) { Console.WriteLine(“This program will determine how ” + “much carpet to purchase.”); Console.WriteLine( ); Console.WriteLine(“You will be asked to enter the ” + “ size of the room and ”); Console.WriteLine(“the price of the carpet, ” + ”in price per square yards.”); Console.WriteLine( ); } class method Call to the method: DisplayInstructions( );

39 Microsoft Visual C#.NET: From Problem Analysis to Program Design39 Writing Your Own Class Methods – void Types ( continued ) public static void DisplayResults(double squareYards, double pricePerSquareYard) { Console.Write(“Total Square Yards needed: ”); Console.WriteLine(“{0:N2}”, squareYards); Console.Write(“Total Cost at {0:C} “, pricePerSquareYard); Console.WriteLine(“ per Square Yard: {0:C}”, (squareYards * pricePerSquareYard)); } static method called from within the class where it resides To invoke method, DisplayResults(16.5, 18.95);

40 Microsoft Visual C#.NET: From Problem Analysis to Program Design40 Value Returning Method Has a return type other than void Must have a return statement –Compatible value Zero, one, or more data items may be passed as arguments Calls can be placed: –In assignment statements –Output statements –Arithmetic expressions –Or anywhere a value can be used

41 Microsoft Visual C#.NET: From Problem Analysis to Program Design41 Value Returning Method ( continued ) public static double GetLength( ) { string inputValue; int feet, inches; Console.Write(“Enter the Length in feet: ”); inputValue = Console.ReadLine( ); feet =int.Parse(inputValue); Console.Write(“Enter the Length in inches: “); inputValue = Console.ReadLine( ); inches = int.Parse(inputValue); return (feet + (double) inches / 12); } Return type→doubl e double returned

42 Microsoft Visual C#.NET: From Problem Analysis to Program Design42 CarpetExampleWithClassMethods /* CarpetExampleWithClassMethods.cs */ using System; namespace CarpetExampleWithClassMethods { public class CarpetWithClassMethods { public static void Main( ) { double roomWidth, roomLength, pricePerSqYard, noOfSquareYards; DisplayInstructions( ); // Call getDimension( ) to get length roomLength = GetDimension(“Length”);

43 Microsoft Visual C#.NET: From Problem Analysis to Program Design43 roomWidth = GetDimension(“Width”); pricePerSqYard = GetPrice( ); noOfSquareYards = DetermineSquareYards(roomWidth, roomLength); DisplayResults(noOfSquareYards, pricePerSqYard); } public static void DisplayInstructions( ) { Console.WriteLine(“This program will determine how much " + “carpet to purchase.”); Console.WriteLine( ); Console.WriteLine("You will be asked to enter the size of ” + “the room "); Console.WriteLine(“and the price of the carpet, in price per” + “ square yds.”); Console.WriteLine( ); }

44 Microsoft Visual C#.NET: From Problem Analysis to Program Design44 public static double GetDimension(string side ) { string inputValue; // local variables int feet, // needed only by this inches; // method Console.Write("Enter the {0} in feet: ", side); inputValue = Console.ReadLine( ); feet = int.Parse(inputValue); Console.Write("Enter the {0} in inches: ", side); inputValue = Console.ReadLine( ); inches = int.Parse(inputValue); // Note: cast required to avoid int division return (feet + (double) inches / 12); }

45 Microsoft Visual C#.NET: From Problem Analysis to Program Design45 public static double GetPrice( ) { string inputValue; // local variables double price; Console.Write(“Enter the price per Square Yard: "); inputValue = Console.ReadLine( ); price = double.Parse(inputValue); return price; } public static double DetermineSquareYards (double width, double length) { const int SQ_FT_PER_SQ_YARD = 9; double noOfSquareYards; noOfSquareYards = length * width / SQ_FT_PER_SQ_YARD; return noOfSquareYards; }

46 Microsoft Visual C#.NET: From Problem Analysis to Program Design46 public static double DeterminePrice (double squareYards, double pricePerSquareYard) { return (pricePerSquareYard * squareYards); } public static void DisplayResults (double squareYards, double pricePerSquareYard) { Console.WriteLine( ); Console.Write(“Square Yards needed: ”); Console.WriteLine("{0:N2}", squareYards); Console.Write("Total Cost at {0:C} ", pricePerSquareYard); Console.WriteLine(“ per Square Yard: {0:C}”, DeterminePrice(squareYards, pricePerSquareYard)); } } }

47 Microsoft Visual C#.NET: From Problem Analysis to Program Design47 CarpetExampleWithClassMethods ( continued )

48 Microsoft Visual C#.NET: From Problem Analysis to Program Design48 The Object Concept Class Entity Abstraction –Attributes (data) –Behaviors (processes on the data) Private member data (fields) –Public method members

49 Microsoft Visual C#.NET: From Problem Analysis to Program Design49 Writing Your Own Instance Methods Do not use static keyword –Static —class method Constructor –Do not return a value –void is not included –Same identifier as the class name –Overloaded methods –Default constructor No arguments

50 Microsoft Visual C#.NET: From Problem Analysis to Program Design50 Writing Your Own Instance Methods ( continued ) Accessor (getter) –Returns just the current value –Standard naming convention → add ”get” in front of instance variable name –Accessor for noOfSquareYardsis GetNoOfSquareYards( ) Mutators (setters) –Normally includes one parameter –Method body → single assignment statement –Standard naming convention add ”Set” to the front of the instance variable identifier

51 Microsoft Visual C#.NET: From Problem Analysis to Program Design51 Accessor and Mutator Examples public double GetNoOfSquareYards( ) { return noOfSquareYards; } public void SetNoOfSquareYards(double squareYards) { noOfSquareYards = squareYards; } Accessor Mutator

52 Microsoft Visual C#.NET: From Problem Analysis to Program Design52 Properties Looks like a data field –More closely aligned to methods Standard naming convention in C# for properties –Use the same name as the instance variable or field, but start with uppercase character

53 Microsoft Visual C#.NET: From Problem Analysis to Program Design53 Calling Instance Methods Calling the Constructor ClassName objectName = new ClassName(argumentList); or ClassName objectName; objectName = new ClassName(argumentList); Keyword new used as operator to call constructor methods CarpetCalculator plush = new CarpetCalculator ( ); CarpetCalculator pile = new CarpetCalculator (37.90, 17.95); CarpetCalculator berber = new CarpetCalculator (17.95);

54 Microsoft Visual C#.NET: From Problem Analysis to Program Design54 Calling Accessor and Mutator Methods Method name is preceded by the object name berber.SetNoOfSquareYards(27.83); Console.WriteLine(“{0:N2}”, berber.GetNoOfSquareYards( )); Using Properties PropertyName = value; And Console.Write(“Total Cost at {0:C} ”, berber.Price);

55 Microsoft Visual C#.NET: From Problem Analysis to Program Design55 Types of Parameters Call by value –copy of the original value is made Other types of parameters –ref –out –params ref and out cause a method to refer to the same variable that was passed into the method

56 Microsoft Visual C#.NET: From Problem Analysis to Program Design56 Types of Parameters ( continued )

57 Microsoft Visual C#.NET: From Problem Analysis to Program Design57 RealEstateInvestment Example

58 Microsoft Visual C#.NET: From Problem Analysis to Program Design58 Data for the RealEstateInvestment Example

59 Microsoft Visual C#.NET: From Problem Analysis to Program Design59 RealEstateInvestment Example ( continued )

60 Microsoft Visual C#.NET: From Problem Analysis to Program Design60 RealEstateInvestment Example ( continued )

61 Microsoft Visual C#.NET: From Problem Analysis to Program Design61 RealEstateInvestment Example ( continued )

62 Microsoft Visual C#.NET: From Problem Analysis to Program Design62

63 Microsoft Visual C#.NET: From Problem Analysis to Program Design63 Chapter Summary Components of a method Class methods –Parameters Predefined methods Value and non-value returning methods

64 Microsoft Visual C#.NET: From Problem Analysis to Program Design64 Chapter Summary ( continued ) Properties Instance methods –Constructors –Mutators –Accessors Types of parameters


Download ppt "Microsoft Visual C#.NET: From Problem Analysis to Program Design1 Chapter 4 Methods and Behaviors Microsoft Visual C#.NET: From Problem Analysis to Program."

Similar presentations


Ads by Google