1 / 60

Console methods Write and WriteLine also have the capability to display formatted data.

3.5  Formatting Text with Console.Write and Console.WriteLine. Outline. Welcome4.cs. Console methods Write and WriteLine also have the capability to display formatted data. Figure 3.17 shows another way to use the WriteLine method. .

pakuna
Télécharger la présentation

Console methods Write and WriteLine also have the capability to display formatted data.

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 3.5  Formatting Text with Console.Write and Console.WriteLine Outline Welcome4.cs • Console methods Write and WriteLine also have the capability to display formatted data. • Figure 3.17 shows another way to use the WriteLine method. Method WriteLine’s first argument is a format string that may consist of fixed text and format items. Fig. 3.17 | Displaying multiple lines of text with string formatting.

  2. Outline Addition.cs (1 of 2 ) Three variables declared as type int. The user is prompted for information. Console.ReadLine() reads the data entered by the user, and Convert.ToInt32 converts the value into an integer. Fig. 3.18 | Displaying the sum of two numbers input fromthe keyboard. (Part 1 of 2).

  3. Outline Addition.cs (2 of 2 ) Fig. 3.18 | Displaying the sum of two numbers input fromthe keyboard. (Part 2 of 2).

  4. Outline • Class GradeBook (Fig. 4.7) maintains the course name as an instance variable so that it can be used or modified. GradeBook.cs (1 of 2 ) Declaring courseName as an instance variable. Fig. 4.7 | GradeBook class that contains a private instance variable,courseName and a public property to get and set its value. (Part 1 of 2).

  5. Outline GradeBook.cs (2 of 2 ) A public property declaration. Fig. 4.7 | GradeBook class that contains a private instance variable, courseName and a public property to get and set its value. (Part 2 of 2).

  6. Outline • Class GradeBookTest (Fig. 4.8) creates a GradeBook object and demonstrates property CourseName. GradeBookTest.cs (1 of 2 ) Creating a GradeBook object and assigning it to local variable myGradeBook. A public property declaration. Fig. 4.8 | Create and manipulate a GradeBook object. (Part 1 of 2).

  7. Outline GradeBookTest.cs (2 of 2 ) Assigns the input course name to myGradeBook’s CourseName property. Calling DisplayMessage for a welcome message. Fig. 4.8 | Create and manipulate a GradeBook object. (Part 2 of 2).

  8. Outline • Figure 4.10 redefines class GradeBook with an auto-implemented CourseName property. GradeBook.cs Declaring the auto-implemented property. Implicitly obtaining the property’s value. Fig. 4.10 | GradeBook class with an auto-implemented property.

  9. Outline • Class GradeBookTest (Fig. 4.8) creates a GradeBook object and demonstrates property CourseName. GradeBookTest.cs (1 of 2 ) Creating a GradeBook object and assigning it to local variable myGradeBook. A public property declaration. Fig. 4.8 | Create and manipulate a GradeBook object. (Part 1 of 2).

  10. Outline GradeBookTest.cs (2 of 2 ) Assigns the input course name to myGradeBook’s CourseName property. Calling DisplayMessage for a welcome message. Fig. 4.8 | Create and manipulate a GradeBook object. (Part 2 of 2).

  11. Outline • A class named Account (Fig. 4.17) maintains the balance of a bank account. Account.cs (1 of 2 ) An instance variable represents each Account’s own balance. The constructor receives a parameter that represents the account’s starting balance. Method Credit receives one parameter named amount that is added to the property Balance. Fig. 4.17 | Account class with a constructor to initialize instancevariable balance. (Part 1 of 2).

  12. Outline Account.cs (2 of 2 ) Balance’s get accessor returns the value of the Account’s balance. Balance’s set accessor performs validation to ensure that value is nonnegative. Fig. 4.17 | Account class with a constructor to initialize instancevariable balance. (Part 2 of 2).

  13. Outline • AccountTest (Fig. 4.18) creates two Account objects and initializes them with 50.00M and -7.53M (decimal literals). AccountTest.cs (1 of 3 ) Passing an initial balance which will be invalidated by Balance’s set accessor. Outputting the Balance property of each Account. Fig. 4.18 | Create and manipulate an Account object. (Part 1 of 3).

  14. Outline AccountTest.cs (2 of 3 ) Local variable deposit­Amount is not initialized to 0 but will be set by the user’s input. Obtaining input from the user. Obtaining the deposit value from the user. Fig. 4.18 | Create and manipulate an Account object. (Part 2 of 3).

  15. Outline AccountTest.cs (3 of 3 ) Outputting the balances of both Accounts. Fig. 4.18 | Create and manipulate an Account object. (Part 3 of 3).

  16. 4.11 Floating-Point Numbers and Type decimal (Cont.) • A value output with the format item {0:C} appears as a monetary amount. • The : indicates that the next character represents a format specifier.

  17. 4.11 Floating-Point Numbers and Type decimal (Cont.) Fig. 4.19|string format specifiers.

  18. 7.3  static Methods, static Variables and Class Math (Cont.) Why Is Method Main Declared static? • The Main method is sometimes called the application’s entry point. • Declaring Main as static allows the execution environment to invoke Main without creating an instance of the class. • When you execute your application from the command line, you type the application name, followed by command-line arguments that specify a list of strings separated by spaces. • The execution environment will pass these arguments to the Main method of your application.

  19. 7.3  static Methods, static Variables and Class Math (Cont.) Additional Comments about Method Main • Applications that do not take command-line arguments may omit the string[] args parameter. • The public keyword may be omitted. • You can declare Main with return type int (instead of void) to enable Main to return an error code with the return statement. • You can declare only one Main method in each class.

  20. 7.3  static Methods, static Variables and Class Math (Cont.) • You can place a Main method in every class you declare. • However, you need to indicate the application’s entry point. • Do this by clicking the menu Project> [ProjectName] Properties... and selecting the class containing the Main method that should be the entry point from the Startupobject list box.

  21. 7.8  The .NET Framework Class Library • Predefined classes are grouped into categories of related classes called namespaces. • Together, these namespaces are referred to as the .NET Framework Class Library.

  22. 7.8  The .NET Framework Class Library (Cont.) • Some key Framework Class Library namespaces are described in Fig. 7.6. Fig. 7.6|Framework Class Library namespaces (a subset). (Part 1 of 2.)

  23. 7.8  The .NET Framework Class Library (Cont.) Fig. 7.6|Framework Class Library namespaces (a subset). (Part 2 of 2.)

  24. 7.8  The .NET Framework Class Library (Cont.) Good Programming Practice 7.2 The online .NET Framework documentation is easy to search and provides many details about each class. As you learn each class in this book, you should review the class in the online documentation for additional information.

  25. Outline Rolling a Six-Sided Die • Figure 7.7 shows two sample outputs of an application that simulates 20 rolls of a six-sideddie and displays each roll’s value. RandomIntegers.cs (1 of 2 ) Create the Random object randomNumbers to produce random values. Fig. 7.7 | Shifted and scaled random integers. (Part 1 of 2.)

  26. Outline RandomIntegers.cs (2 of 2 ) Call Next with two arguments. Fig. 7.7 | Shifted and scaled random integers. (Part 2 of 2.)

  27. Outline • The declaration of class Craps is shown in Fig. 7.9. Craps.cs (1 of 4 ) A user-defined type called an enumeration declares a set of constants represented by identifiers, and is introduced by the keyword enum and a type name. Fig. 7.9 | Craps class simulates the dice game craps. (Part 1 of 4.)

  28. Outline Craps.cs (2 of 4 ) Sums of the dice that would result in a win or loss on the first roll are declared in an enumeration. Initialization is not strictly necessary because it is assigned a value in every branch of the switch statement. Must be initialized to 0 because it is not assigned a value in every branch of the switch statement. Call method RollDice for the first roll of the game. Fig. 7.9 | Craps class simulates the dice game craps. (Part 2 of 4.)

  29. Outline Craps.cs (3 of 4 ) Call method RollDice for subsequent rolls. Fig. 7.9 | Craps class simulates the dice game craps. (Part 3 of 4.)

  30. Outline Craps.cs (4 of 4 ) Declare method RollDice to roll the dice and compute and display their sum. Fig. 7.9 | Craps class simulates the dice game craps. (Part 4 of 4.)

  31. 7.10  Case Study: A Game of Chance (Introducing Enumerations) (Cont.) • You can declare an enum’s underlying type to be byte, sbyte, short, ushort, int, uint, long or ulong by writing privateenumMyEnum : typeName{Constant1,Constant2,...} • typeName represents one of the integral simple types. • To compare a simple integral type value to the underlying value of an enumeration constant, you must use a cast operator.

  32. 7.14  Passing Arguments: Pass-by-Value vs. Pass-by-Reference • Two ways to pass arguments to functions in many programming languages are pass-by-value andpass-by-reference. • When an argument is passed by value (the default in C#), a copy of its value is made and passed to the called function. • When an argument is passed by reference, the caller gives the method the ability to access and modify the caller’s original variable.

  33. 7.14  Passing Arguments: Pass-by-Value vs. Pass-by-Reference (Cont.) Performance Tip 7.1 Pass-by-reference is good for performance reasons, becauseit can eliminate the pass-by-value overhead of copying large amounts of data. Software Engineering Observation 7.5 Pass-by-reference can weaken security, because the called function can corrupt the caller’s data.

  34. 7.14  Passing Arguments: Pass-by-Value vs. Pass-by-Reference (Cont.) • To pass an object by reference into a method, simply provide as an argument in the method call the variable that refers to the object. • In the method body, the parameter will refer to the original object in memory, so the called method can access the original object directly. • Passing a value-type variable to a method passes a copy of the value.

  35. 7.14  Passing Arguments: Pass-by-Value vs. Pass-by-Reference (Cont.) • Passing a reference-type variable passes the method a copy of the actual reference that refers to the object. • The reference itself is passed by value, but the method can still use the reference it receives to modify the original object in memory. • A return statement returns a copy of the value stored in a value-type variable or a copy of the reference stored in a reference-type variable. • In effect, objects are always passed by reference.

  36. 7.14  Passing Arguments: Pass-by-Value vs. Pass-by-Reference (Cont.) • Applying the ref keyword to a parameter declaration allows you to pass a variable to a method by reference • The ref keyword is used for variables that already have been initialized in the calling method. • Preceding a parameter with keyword out creates an output parameter. • This indicates to the compiler that the argument will be passed by reference and that the called method will assign a value to it. • A method can return multiple output parameters.

  37. Outline • Class ReferenceAndOutputParameters (Fig. 7.18) contains three methods that calculate the square of an integer. ReferenceAndOutputParameters.cs ( 1 of 4 ) Fig. 7.18 | Reference, output and value parameters. (Part 1 of 4.)

  38. Outline ReferenceAndOutputParameters.cs ( 2 of 4 ) When you pass a variable to a method with a reference parameter, you must precede the argument with the same keyword (ref or out) that was used to declare the reference parameter. Fig. 7.18 | Reference, output and value parameters. (Part 2 of 4.)

  39. Outline ReferenceAndOutputParameters.cs ( 3 of 4 ) Modify caller’s x. Fig. 7.18 | Reference, output and value parameters. (Part 3 of 4.)

  40. Outline ReferenceAndOutputParameters.cs ( 4 of 4 ) Assign a value to caller’s uninitialized x. Doesn’t modify any caller variable. Fig. 7.18 | Reference, output and value parameters. (Part 4 of 4.)

  41. 7.14  Passing Arguments: Pass-by-Value vs. Pass-by-Reference (Cont.) • When you pass a variable to a method with a reference parameter, you must precede the argument with the same keyword (ref or out) that was used to declare the reference parameter. Common Programming Error 7.12 The ref and out arguments in a method call must match the parameters specified in the method declaration; otherwise, a compilation error occurs.

  42. 7.14  Passing Arguments: Pass-by-Value vs. Pass-by-Reference (Cont.) Software Engineering Observation 7.6 By default, C# does not allow you to choose whether to pass each argument by value or by reference. Value types are passed by value. Objects are not passed to methods; rather, references to objects are passed to methods. The references themselves are passed by value. When a method receives a reference to an object, the method can manipulate the object directly, but the reference value cannot be changed to refer to a new object.

  43. Outline • Class ReferenceAndOutputParametersTest tests the ReferenceAndOutputParameters class. ReferenceAndOutputParamtersTest.cs Fig. 7.19 | Application to test class ReferenceAndOutputParameters.

  44. 8.6  foreach Statement • The foreach statement iterates through the elements of an entire array or collection. • The syntax of a foreach statement is: foreach ( type identifierinarrayName )statement • type and identifier are the type and name (e.g., intnumber) of the iteration variable. • arrayName is the array through which to iterate. • The type of the iteration variable must match the type of the elements in the array. • The iteration variable represents successive values in the array on successive iterations of the foreach statement.

  45. Outline • Figure 8.12 uses the foreach statement to calculate the sum of the integers in an array of student grades. ForEachTest.cs ( 1 of 2 ) For each iteration, number represents the next int value in the array. Fig. 8.12 | Using the foreach statement to total integers in an array.

  46. 8.6  foreach Statement (Cont.) Implicitly Typed Local Variables • C# provides a new feature—called implicitly typed local variables—that enables the compiler to infer a local variable’s type based on the type of the variable’s initializer. • To distinguish such an initialization from a simple assignment statement, the var keyword is used in place of the variable’s type. • The compiler assumes that floating-point number values are of type double. • You can use local type inference with control variables in the header of a for or foreach statement. • For example, the following for statement headers are equivalent: for ( int counter = 1; counter < 10; counter++ ) for ( var counter = 1; counter < 10; counter++ )

  47. 8.6  foreach Statement (Cont.) • Similarly, if myArray is an array of ints, the following foreach statement headers are equivalent: foreach (int number in myArray) foreach (var number in myArray) • The implicitly typed local-variable feature is one of several new Visual C# 2008 features that support Language Integrated Query (LINQ). • Implicitly typed local variables can be also used to initialize arrays without explicitly giving their type. • There are no square brackets on the left side of the assignment operator. • new[] is used on the right to specify that the variable is an array.

  48. 8.8  Passing Arrays by Value and by Reference (Cont.) • You can use keyword ref to pass a reference-type variable by reference, which allows the called method to modify the original variable in the caller and make that variable refer to a different object. • This is a subtle capability, which, if misused, can lead to problems.

  49. Outline • The application in Fig. 8.14 demonstrates the subtle difference between passing a reference by value and passing a reference by reference with keyword ref. ArrayReferenceTest.cs ( 1 of 5 ) Fig. 8.14 | Passing an array reference by value and by reference. (Part 1 of 5.)

  50. Outline ArrayReferenceTest.cs ( 2 of 5 ) Fig. 8.14 | Passing an array reference by value and by reference. (Part 2 of 5.)

More Related