Declaring Methods with Multiple Parameters

Một phần của tài liệu Visual C 2012 How to Program _ www.bit.ly/taiho123 (Trang 277 - 281)

2. When the app executes, another compiler (known as the just-in-time compiler

7.4 Declaring Methods with Multiple Parameters

We now consider how to write your own methods with multiple parameters. The app in Fig. 7.3 uses a user-defined method calledMaximumto determine and return the largest of

Common Programming Error 7.1

Every constant declared in a class, but not inside a method of the class is implicitlystatic, so it’s a syntax error to declare such a constant with keywordstaticexplicitly.

public static void Main( string args[] )

AppName argument1 argument2

7.4 Declaring Methods with Multiple Parameters 237

threedoublevalues. When the app begins execution, theMainmethod (lines 8–22) exe- cutes. Line 18 calls methodMaximum(declared in lines 25–38) to determine and return the largest of the threedoublevalues. At the end of this section, we’ll discuss the use of oper- ator + in line 21.

1 // Fig. 7.3: MaximumFinder.cs 2 // User-defined method Maximum.

3 using System;

4

5 public class MaximumFinder 6 {

7 // obtain three floating-point values and determine maximum value 8 public static void Main( string[] args )

9 {

10 // prompt for and input three floating-point values

11 Console.WriteLine( "Enter three floating-point values,\n" + 12 " pressing 'Enter' after each one: " );

13 double number1 = Convert.ToDouble( Console.ReadLine() );

14 double number2 = Convert.ToDouble( Console.ReadLine() );

15 double number3 = Convert.ToDouble( Console.ReadLine() );

16

17 // determine the maximum value

18 ;

19

20 // display maximum value

21 Console.WriteLine( );

22 } // end Main 23

24 25 26 27 28 29 30 31 32 33 34 35 36 37 38

39 } // end class MaximumFinder

Enter three floating-point values, pressing 'Enter' after each one:

2.22 3.33 1.11

Maximum is: 3.33

Fig. 7.3 | User-defined methodMaximum.

double result = Maximum( number1, number2, number3 )

"Maximum is: " + result

// returns the maximum of its three double parameters public static double Maximum( double x, double y, double z ) {

double maximumValue = x; // assume x is the largest to start // determine whether y is greater than maximumValue

if ( y > maximumValue ) maximumValue = y;

// determine whether z is greater than maximumValue if ( z > maximumValue )

maximumValue = z;

return maximumValue;

} // end method Maximum

ThepublicandstaticKeywords

MethodMaximum’s declaration begins with keywordpublicto indicate that the method is

“available to the public”—it can be called from methods of other classes. The keyword

staticenables theMainmethod (another staticmethod) to callMaximumas shown in line 18 without qualifying the method name with the class nameMaximumFinder—static methods in thesameclass can call each other directly. Any other class that usesMaximum must fully qualify the method name with the class name.

MethodMaximum

Consider the declaration of method Maximum (lines 25–38). Line 25 indicates that the method returns adoublevalue, that the method’s name isMaximumand that the method requiresthreedoubleparameters (x,yandz) to accomplish its task. When a method has more than one parameter, the parameters are specified as acomma-separated list. When

Maximumis called in line 18, the parameterxis initialized with the value of the argument

number1, the parameteryis initialized with the value of the argumentnumber2 and the parameterz is initialized with the value of the argumentnumber3. There must be one argument in the method call for each required parameter (sometimes called a formal parameter) in the method declaration. Also, each argument must beconsistent with the type of the corresponding parameter. For example, a parameter of typedoublecan receive values like 7.35(a double),22 (anint) or –0.03456(a double), but not strings like

"hello". Section 7.7 discusses the argument types that can be provided in a method call for each parameter of a simple type.

Logic of Determining the Maximum Value

To determine the maximum value, we begin with the assumption that parameterxcon- tains the largest value, so line 27 declares local variablemaximumValueand initializes it with the value of parameterx. Of course, it’s possible that parameteryorzcontains the largest value, so we must compare each of these values withmaximumValue. Theifstatement at lines 30–31 determines whetheryis greater thanmaximumValue. If so, line 31 assignsyto

maximumValue. Theifstatement at lines 34–35 determines whetherzis greater thanmax-

imumValue. If so, line 35 assignsztomaximumValue. At this point, the largest of the three values resides inmaximumValue, so line 37 returns that value to line 18. When program control returns to the point in the app whereMaximumwas called,Maximum’s parametersx,

yandzare no longer accessible. Methods can returnat most onevalue; the returned value can be a value type that contains one or more values (implemented as astruct) or a ref- erence to an object that contains one or more values.

When to Declare Variables as Fields of a Class

Variableresultis a local variable in methodMainbecause it’s declared in the block that represents the method’s body. Variables should be declared as fields of a class (i.e., as either instance variables orstaticvariables of the class)onlyif they’re required for use in more than one method of the class or if the app should save their values between calls to a given method.

Common Programming Error 7.2

Declaring method parameters of the same type asdouble x, yinstead ofdouble x,

double yis a syntax error—a type is required for each parameter in the parameter list.

7.4 Declaring Methods with Multiple Parameters 239

Implementing MethodMaximumby Reusing MethodMath.Max

Recall from Fig. 7.2 that classMathhas aMaxmethod that can determine the larger of two values. The entire body of our maximum method could also be implemented with nested calls toMath.Max, as follows:

The leftmost call toMath.Maxspecifies arguments xandMath.Max( y, z ). Before any method can be called, the .NET runtime evaluatesallits arguments to determine their val- ues. If an argument is a method call, the method call must be performed to determine its return value. So, in the preceding statement,Math.Max( y, z )is evaluated first to deter- mine the maximum ofyandz. Then the result is passed as the second argument to the other call toMath.Max, which returns the larger of its two arguments. UsingMath.Maxin this manner is a good example ofsoftware reuse—we find the largest of three values by re- usingMath.Max, which finds the larger of two values. Note how concise this code is com- pared to lines 27–37 of Fig. 7.3.

Assembling Strings with String Concatenation

C# allowsstringobjects to be created by assembling smallerstrings into largerstrings using operator+(or the compound assignment operator+=). This is known asstringcon- catenation. When both operands of operator+arestringobjects, operator+creates a new

stringobject in which a copy of the characters of therightoperand is placed at the end of a copy of the characters in theleftoperand. For example, the expression"hello " + "there"

creates thestring "hello there"without disturbing the originalstrings.

In line 21 of Fig. 7.3, the expression"Maximum is: " + resultuses operator+with operands of typesstringanddouble. Every value of a simple type in C# has astring representation. When one of the+operator’s operands is astring, the other is implicitly converted to astring, then the two areconcatenated. In line 21, thedoublevalue isimplic- itlyconverted to itsstringrepresentation and placed at the end of thestring "Maximum is: ". If there are any trailing zeros in adoublevalue, these will bediscardedwhen the number is converted to astring. Thus, the number 9.3500 would be represented as 9.35 in the resultingstring.

Anything Can Be Converted to astring

For values of simple types used in string concatenation, the values are converted to

strings. If abool is concatenated with astring, the boolis converted to the string

"True" or"False"(each is capitalized). All objects have aToStringmethod that returns astringrepresentation of the object. When an object is concatenated with astring, the object’sToStringmethod is calledimplicitlyto obtain thestringrepresentation of the object. If the object isnull, anempty stringis written.

Outputtingstrings with Format Items

Line 21 of Fig. 7.3 could also be written usingstringformatting as

As withstringconcatenation, using a format item to substitute an object into astring implicitlycalls the object’sToStringmethod to obtain the object’sstringrepresentation.

You’ll learn more about methodToStringin Chapter 8.

return Math.Max( x, Math.Max( y, z ) );

Console.WriteLine( "Maximum is: {0}", result );

Breaking a LargestringLiteral into Smallerstrings

When a largestringliteral is typed into an app’s source code, you can break thatstring into several smallerstrings and place them on multiple lines for readability. Thestrings can be reassembled using either string concatenation or string formatting. We discuss the details ofstrings in Chapter 16.

Một phần của tài liệu Visual C 2012 How to Program _ www.bit.ly/taiho123 (Trang 277 - 281)

Tải bản đầy đủ (PDF)

(1.020 trang)