9781285096261 ch08 PPT - csuohio.educis.csuohio.edu/.../9781285096261_ch08_PPT_Handout.pdf ·...

31
8/29/2015 1 Ad d 8 Advanced Collections 8 C# Programming: From Problem Analysis to Program Design 1 C# Programming: From Problem Analysis to Program Design 4th Edition Chapter Objectives Create two-dimensional arrays including rectangular and Create two dimensional arrays including rectangular and jagged types Use multidimensional arrays Use the ArrayList class to create dynamic lists C# Programming: From Problem Analysis to Program Design 2 Learn about the predefined methods of the string class

Transcript of 9781285096261 ch08 PPT - csuohio.educis.csuohio.edu/.../9781285096261_ch08_PPT_Handout.pdf ·...

Page 1: 9781285096261 ch08 PPT - csuohio.educis.csuohio.edu/.../9781285096261_ch08_PPT_Handout.pdf · follow same guidelines as one-dimensional ... • Notice how each row is grouped using

8/29/2015

1

Ad d8 Advanced

Collections8C# Programming: From Problem Analysis to Program Design 1

C# Programming: From Problem Analysis to Program Design 4th Edition

Chapter Objectives

• Create two-dimensional arrays including rectangular andCreate two dimensional arrays including rectangular and jagged types

• Use multidimensional arrays

• Use the ArrayList class to create dynamic lists

C# Programming: From Problem Analysis to Program Design 2

• Learn about the predefined methods of the string class

Page 2: 9781285096261 ch08 PPT - csuohio.educis.csuohio.edu/.../9781285096261_ch08_PPT_Handout.pdf · follow same guidelines as one-dimensional ... • Notice how each row is grouped using

8/29/2015

2

Chapter Objectives (continued)

• Be introduced to the other collection classes

• Work through a programming example that illustrates the chapter’s concepts

C# Programming: From Problem Analysis to Program Design 3

Two-Dimensional Arrays• Two-dimensional and other multidimensional arrays

follow same guidelines as one-dimensional

• Two kinds of two-dimensional arrays

– Rectangular• Visualized as a table divided into rows and columns

– Jagged or ragged

• Referenced much like you reference a matrix

C# Programming: From Problem Analysis to Program Design 4

Page 3: 9781285096261 ch08 PPT - csuohio.educis.csuohio.edu/.../9781285096261_ch08_PPT_Handout.pdf · follow same guidelines as one-dimensional ... • Notice how each row is grouped using

8/29/2015

3

Two-Dimensional Arrays (continued)

int [ , ] calories =  { {900, 750, 1020}, {300, 1000, 2700},

{500, 700, 2100}, {400, 900, 1780},

{600, 1200, 1100}, {575, 1150, 1900},

{600, 1020, 1700}    };

• Notice how each row is grouped using curly braces.

• A comma is used to separate rows

• Values are stored side by side in contiguous memory locations using a row major format

C# Programming: From Problem Analysis to Program Design 5

Two-Dimensional Representation

C# Programming: From Problem Analysis to Program Design 6

Figure 8-1 Two-dimensional structure

Page 4: 9781285096261 ch08 PPT - csuohio.educis.csuohio.edu/.../9781285096261_ch08_PPT_Handout.pdf · follow same guidelines as one-dimensional ... • Notice how each row is grouped using

8/29/2015

4

Two-Dimensional Arrays (continued)

• Declaration formatDeclaration formattype [ , ] identifier = new type [integral value, integral value]; 

– Two integral values are required for a two-dimensional array (number of rows listed first)

• Data values placed in array must be of the same base type

C# Programming: From Problem Analysis to Program Design 7

• Example (create a 7x3 matrix)int [ , ] calories = new int[7, 3];

Two-Dimensional Arrays (continued)

caloriescalories references address of

calories[0,0]

C# Programming: From Problem Analysis to Program Design 8

Figure 8-2 Two-dimensional calories array

Page 5: 9781285096261 ch08 PPT - csuohio.educis.csuohio.edu/.../9781285096261_ch08_PPT_Handout.pdf · follow same guidelines as one-dimensional ... • Notice how each row is grouped using

8/29/2015

5

Two-Dimensional Arrays (continued)

• Length property gets total number of elements in all e gt p ope ty gets tota u be o e e e ts adimensionsConsole.WriteLine(calories.Length);    // Returns 21 

• GetLength( ) – returns the number of rows or columns– GetLength(0) returns number of rows– GetLength(1) returns number of columns

C# Programming: From Problem Analysis to Program Design 9

Console.WriteLine(calories.GetLength(1));   //Display 3  (columns)

Console.WriteLine(calories.GetLength(0));   //Display 7  (rows)

Console.WriteLine(calories.Rank);           // returns 2 (# dimen)

Two-Dimensional Arrays (continued)

int [ , ] calories = new int[7, 3];[ ] [ ]Console.WriteLine(calories.GetUpperBound(0)); // Returns 6 (row index)

foreach (int cal in calories) // Displays all valuesConsole.Write(cal + " ");

for (int r = 0; r < calories.GetLength(0); r++)for (int c = 0; c < calories.GetLength(1); c++)( ; g ( ); )

calories[r, c] = 0; // Initializes all cells (redundant)

C# Programming: From Problem Analysis to Program Design 10

Page 6: 9781285096261 ch08 PPT - csuohio.educis.csuohio.edu/.../9781285096261_ch08_PPT_Handout.pdf · follow same guidelines as one-dimensional ... • Notice how each row is grouped using

8/29/2015

6

Two-Dimensional Arrays (continued)

public static double[ ] CalculateAverageByDay (int[ , ] calories){

i 0Method returns array of a erages ro a eragesint sum = 0;

double[ ] dailyAverage = new double[7];for (int r = 0; r < calories.GetLength(0); r++){for (int c = 0; c < calories.GetLength(1); c++)

sum += calories[r, c];dailyAverage[r] = (double)sum / calories.GetLength(1);

averages…row averages

sum = 0;}return dailyAverage;

}

C# Programming: From Problem Analysis to Program Design 11

Two-Dimensional Arrays (continued)

public static double[ ] CalculateAverageByMeal(int[ , ] calories){

i 0Method returns array of a erages col a eragesint sum = 0;

double[ ] mealAverage = new double[3];for (int c = 0; c < calories.GetLength(1); c++){for (int r = 0; r < calories.GetLength(0); r++)

sum += calories[r, c];mealAverage[c] = (double)sum / calories.GetLength(0);

averages…col averages

sum = 0;}return mealAverage;

}

C# Programming: From Problem Analysis to Program Design 12

Page 7: 9781285096261 ch08 PPT - csuohio.educis.csuohio.edu/.../9781285096261_ch08_PPT_Handout.pdf · follow same guidelines as one-dimensional ... • Notice how each row is grouped using

8/29/2015

7

Two-Dimensional Arrays (continued)

public static void DisplayAverageCaloriesPerMeal (int[ , ] calories){

double sum = 0;double sum = 0;for (int day = 0; day < calories.GetLength(0); day++)

for (int meal = 0; meal < calories.GetLength(1); meal++)sum += calories[day, meal];

Console.WriteLine("\nCaloric Average Per Meal: {0:N0}",sum / calories.Length);

}

• Better:Control variables day and meal used as row/col identifiers → more representative of the data

C# Programming: From Problem Analysis to Program Design 13

Review WeeklyCalorieCounter Example

Two-Dimensional Arrays (continued)

C# Programming: From Problem Analysis to Program Design 14

Figure 8-3 Output from WeeklyCalorieCounter

Page 8: 9781285096261 ch08 PPT - csuohio.educis.csuohio.edu/.../9781285096261_ch08_PPT_Handout.pdf · follow same guidelines as one-dimensional ... • Notice how each row is grouped using

8/29/2015

8

Two-Dimensional Arrays (continued)

• To align numbers for output format specifier used• To align numbers for output, format specifier usedConsole.WriteLine("{0,-10}: {1,6}", mealTime[c ],

mealAverage[c ].ToString("N0"));

– Comma separates placeholder index from width specifier

– First argument ({0,-10}) indicates that the first argument should be displayed in a width of 10

– Negative value in front of the 10 indicates the value should gbe left justified

– Second argument ({1,6}) indicates the numbers are right justified in a width of 6 character positions

C# Programming: From Problem Analysis to Program Design 15

Jagged Arrays• Rectangular arrays always have a rectangular shape, like a

table; jagged arrays do nottable; jagged arrays do not

• Also called ‘arrays of arrays’

• Exampleint[ ] [ ] anArray = new int[4] [ ];anArray [0] = new int[ ] {100, 200};anArray [1] = new int[ ] {11, 22, 37};

C# Programming: From Problem Analysis to Program Design 16

anArray [2] = new int[ ] {16, 72, 83, 99, 106};anArray [3] = new int[ ] {1, 2, 3, 4};

Page 9: 9781285096261 ch08 PPT - csuohio.educis.csuohio.edu/.../9781285096261_ch08_PPT_Handout.pdf · follow same guidelines as one-dimensional ... • Notice how each row is grouped using

8/29/2015

9

Multidimensional Arrays• Limited only by your imagination as far as the number of

dimensionsdimensions

• Format for creating three-dimensional arraytype [ , , ] identifier =

new type [integral value, integral value, integral value];

• Example (rectangular)int [ , , ] calories = new int [4 ,7 ,3];

C# Programming: From Problem Analysis to Program Design 17

int [ , , ] calories new int [4 ,7 ,3];

(4 week; 7 days; 3 meals) Allocates storage for 84 elements

Multidimensional Arrays (continued)

Figure 8-4 Three-dimensional array

C# Programming: From Problem Analysis to Program Design 18

Upper bounds on the indexes

are 3, 6, 2

Page 10: 9781285096261 ch08 PPT - csuohio.educis.csuohio.edu/.../9781285096261_ch08_PPT_Handout.pdf · follow same guidelines as one-dimensional ... • Notice how each row is grouped using

8/29/2015

10

Multidimensional Arrays (continued)

int [ , , ] calories = new int [4, 7, 4];// Loop to place the row total in the last column, indexed by 3for (int wk = 0; wk < calories.GetLength(0); wk++){

for (int da = 0; da < calories.GetLength(1); da++){

for (int ml = 0; ml < calories.GetLength(2) - 1; ml++){

calories[wk, da, 3] += calories[wk, da, ml];[ , , ] [ , , ];}

}}

C# Programming: From Problem Analysis to Program Design 19

Review CalorieCounter Example

Multidimensional Arrays (continued)

Index from the calories array for the daynumber used as index for

C# Programming: From Problem Analysis to Program Design 20

the string day name array

Page 11: 9781285096261 ch08 PPT - csuohio.educis.csuohio.edu/.../9781285096261_ch08_PPT_Handout.pdf · follow same guidelines as one-dimensional ... • Notice how each row is grouped using

8/29/2015

11

ArrayList Class • Limitations of traditional array

C t h th i l th f ft it i– Cannot change the size or length of an array after it is created

• ArrayList class facilitates creating listlike structure, AND it can dynamically increase or decrease in length

– Similar to vector class found in other languages

C# Programming: From Problem Analysis to Program Design 21

• Includes large number of predefined methods

ArrayList Class (continued)

C# Programming: From Problem Analysis to Program Design 22

Table 8-1 ArrayList members

Page 12: 9781285096261 ch08 PPT - csuohio.educis.csuohio.edu/.../9781285096261_ch08_PPT_Handout.pdf · follow same guidelines as one-dimensional ... • Notice how each row is grouped using

8/29/2015

12

ArrayList Class (continued)

C# Programming: From Problem Analysis to Program Design 23

Table 8-1 ArrayList members (continued)

ArrayList Class (continued)

C# Programming: From Problem Analysis to Program Design 24

Table 8-1 ArrayList members (continued)

Page 13: 9781285096261 ch08 PPT - csuohio.educis.csuohio.edu/.../9781285096261_ch08_PPT_Handout.pdf · follow same guidelines as one-dimensional ... • Notice how each row is grouped using

8/29/2015

13

ArrayList Class (continued)

• Any predefined or user-defined type can be used as anAny predefined or user defined type can be used as an ArrayList object

• C# also includes a (better & safer) List< > class

– List< > class requires that objects be of the same type when you place them in the structure

A Li t ll t i t ( f ti )– ArrayList allows you to mix types (unsafe practice)

C# Programming: From Problem Analysis to Program Design 25

ArrayList Class (continued)

ArrayList anArray = new ArrayList( ); // Instantiates ArrayListy y y ( ); y

anArray.Add("Today is the first day of the rest of your life!");anArray.Add("Live it to the fullest!");anArray.Add("ok");anArray.Add("You may not get a second chance.");

anArray.RemoveAt(2); // Removes the third physical one (“ok”)

for (int i = 0; i < anArray.Count; i++) //Displays elementsConsole.WriteLine(anArray[i] );

C# Programming: From Problem Analysis to Program Design 26

Page 14: 9781285096261 ch08 PPT - csuohio.educis.csuohio.edu/.../9781285096261_ch08_PPT_Handout.pdf · follow same guidelines as one-dimensional ... • Notice how each row is grouped using

8/29/2015

14

ArrayList Class (continued)

C# Programming: From Problem Analysis to Program Design 27

Review ArrayListExample

Figure 8-6 Sample run from the ArrayList example

String Class • Stores a collection of Unicode characters

I t bl i f h t• Immutable series of characters

• Reference type

– Normally equality operators, == and !=, compare the object’s references, but operators function differently with string than with other reference objects

• Equality operators are defined to compare the contents or l

C# Programming: From Problem Analysis to Program Design 28

values

• Includes large number of predefined methods

Page 15: 9781285096261 ch08 PPT - csuohio.educis.csuohio.edu/.../9781285096261_ch08_PPT_Handout.pdf · follow same guidelines as one-dimensional ... • Notice how each row is grouped using

8/29/2015

15

String Class

• Can process variables of string type as a group of charactersCan process variables of string type as a group of characters

– Can also access individual characters in string using an index with [ ]

• First character is indexed by zero

string sValue = "C# Programming";

object sObj;object sObj;

string s = "C#";

C# Programming: From Problem Analysis to Program Design 29

The declarations used with

Examples in Table 8-2 on next slide

C# Programming: From Problem Analysis to Program Design 30

Table 8-2 Members of the string class

Page 16: 9781285096261 ch08 PPT - csuohio.educis.csuohio.edu/.../9781285096261_ch08_PPT_Handout.pdf · follow same guidelines as one-dimensional ... • Notice how each row is grouped using

8/29/2015

16

C# Programming: From Problem Analysis to Program Design 31

Table 8-2 Members of the string class (continued)

C# Programming: From Problem Analysis to Program Design 32

Table 8-2 Members of the string class (continued)

Page 17: 9781285096261 ch08 PPT - csuohio.educis.csuohio.edu/.../9781285096261_ch08_PPT_Handout.pdf · follow same guidelines as one-dimensional ... • Notice how each row is grouped using

8/29/2015

17

C# Programming: From Problem Analysis to Program Design 33

Table 8-2 Members of the string class (continued)

C# Programming: From Problem Analysis to Program Design 34Table 8-2 Members of the string class (continued)

Page 18: 9781285096261 ch08 PPT - csuohio.educis.csuohio.edu/.../9781285096261_ch08_PPT_Handout.pdf · follow same guidelines as one-dimensional ... • Notice how each row is grouped using

8/29/2015

18

C# Programming: From Problem Analysis to Program Design 35

Table 8-2 Members of the string class (continued)

C# Programming: From Problem Analysis to Program Design 36

Table 8-2 Members of the string class (continued)

Page 19: 9781285096261 ch08 PPT - csuohio.educis.csuohio.edu/.../9781285096261_ch08_PPT_Handout.pdf · follow same guidelines as one-dimensional ... • Notice how each row is grouped using

8/29/2015

19

C# Programming: From Problem Analysis to Program Design 37

Table 8-2 Members of the string class (continued)

String Class

• Class methods, such as Compare, Concat, and Copy, prefix the name , p , , py, pof the method in the call with the string data type (e.g. s = string.Copy(sValue);).

• Most string member arguments that take a string object accept a string literal

– @-quoted string literals, start with the @ symbolConsole.WriteLine(@"hello \t world");

//Displays hello \t world

C# Programming: From Problem Analysis to Program Design 38

Page 20: 9781285096261 ch08 PPT - csuohio.educis.csuohio.edu/.../9781285096261_ch08_PPT_Handout.pdf · follow same guidelines as one-dimensional ... • Notice how each row is grouped using

8/29/2015

20

Other Collection Classes

• Collection classes are classes that enable you to store andCollection classes are classes that enable you to store and retrieve various groups of objects

• Number of other predefined collection classes– BitArray

– HashTable

HashSet– HashSet

– Stack

– Queue

– LinkedList

C# Programming: From Problem Analysis to Program Design 39

BitArray class

• Bit values are represented as BooleansBit values are represented as Booleans

• Include the System.Collections namespace// Creates and initializes several BitArraysBitArray firstBitArr = new BitArray(10);BitArray secondBitArr = new BitArray(10, true);bool[ ] boolArray = new bool[5] {true, false, true, true, false};BitArray thirdBitArr = new BitArray(boolArray);

• Count and Length properties

• Item property

C# Programming: From Problem Analysis to Program Design 40

Page 21: 9781285096261 ch08 PPT - csuohio.educis.csuohio.edu/.../9781285096261_ch08_PPT_Handout.pdf · follow same guidelines as one-dimensional ... • Notice how each row is grouped using

8/29/2015

21

BitArray class (continued)

• Set( ) and SetAll ( ) methodsSet( ) and SetAll ( ) methods– BitArrays most commonly used to represent a simple group of Boolean

flags

– BitArrays useful for working with large data sets

C# Programming: From Problem Analysis to Program Design 41

HashTable class

• Hashtable represents a collection of <key,value> pairs thatHashtable represents a collection of <key,value> pairs that are organized based on the hash code of the key

• Hash code - a number generated using a key with the objective of providing efficient insertion and find operations

• Overriding goal is to design an algorithm that provides as few collisions as possiblep

• Do not have to create your own algorithm when you use the .NET Hashtable class

C# Programming: From Problem Analysis to Program Design 42

Page 22: 9781285096261 ch08 PPT - csuohio.educis.csuohio.edu/.../9781285096261_ch08_PPT_Handout.pdf · follow same guidelines as one-dimensional ... • Notice how each row is grouped using

8/29/2015

22

HashTable class (continued)

// Creates a new hash table

Hashtable hTable= new Hashtable();

// Add some elements to the hash table. There are no

// dup. keys, but some of the values are duplicates.

hTable.Add("pdf", "acrord32.exe");

hTable.Add("tif", "snagit32.exe");

hTableAdd("jpg", "snagit32.exe");( jpg , g );

hTable.Add("sln", "devenv.exe");

hTable.Add("rtf", "wordpad.exe"); 

Console.WriteLine(hTable2["pdf"]); //acrord32.exe

C# Programming: From Problem Analysis to Program Design 43

HashTable class (continued)

• To write your own hash algorithm override theTo write your own hash algorithm, override the GetHashCode() method and provide a new algorithm for the hash function– Should also override the Equals() method to guarantee that two

objects considered equal have the same hash code

• Has properties and methods: Add(), Clear(),    p p () ()

Contains(), Count, Keys, Item, Remove(), and Values

C# Programming: From Problem Analysis to Program Design 44

Page 23: 9781285096261 ch08 PPT - csuohio.educis.csuohio.edu/.../9781285096261_ch08_PPT_Handout.pdf · follow same guidelines as one-dimensional ... • Notice how each row is grouped using

8/29/2015

23

Linked List

• Linked lists have additional field that contains a referenceLinked lists have additional field that contains a reference (link) to next record in the sequence– Records do not have to be physically stored beside each other to

retain their order

– Enables insertion and removal of records at any point in the list

– Insertion involves adjustment of links to point to newly inserted element

– Deletion involves adjustment of links to not point to deleted node

– Some methods are: AddAfter, AddBefore, AddFirst, AddLast, Clear, Contains, Find, FindLast, Remove, RemoveFirst, RemoveLast, ElementAt

C# Programming: From Problem Analysis to Program Design 45

Linked List

// Create the link list. 

string[] words = {"the", "fox", "jumped", "over", "the", "dog" };

LinkedList<string> sentence = new LinkedList<string>(words);

foreach (string word in sentence)

{

Console.WriteLine("LinkedList... " + word);

}}

C# Programming: From Problem Analysis to Program Design 46

Page 24: 9781285096261 ch08 PPT - csuohio.educis.csuohio.edu/.../9781285096261_ch08_PPT_Handout.pdf · follow same guidelines as one-dimensional ... • Notice how each row is grouped using

8/29/2015

24

Queue

• First-In-First-Out (FIFO) collection of objectsFirst In First Out (FIFO) collection of objects

• Useful for storing objects in the order they were received for sequential processing

• Capacity of a queue is the number of elements the queue can hold

• Enqueue() adds an object to the end of the queue

• Dequeue() removes and returns object at the beginning of the queue

C# Programming: From Problem Analysis to Program Design 47

Stack

• Last-in-first-out (LIFO) collection of objectsLast in first out (LIFO) collection of objects

• As elements are added, the capacity is automatically increased

• Push() adds an object to the end of the stack

• Pop() removes and returns the object to the beginning of the stack

• Peak() returns the object at the beginning of the stack without removing it Queue also has a Peak() method

C# Programming: From Problem Analysis to Program Design 48

Review StackExample

Page 25: 9781285096261 ch08 PPT - csuohio.educis.csuohio.edu/.../9781285096261_ch08_PPT_Handout.pdf · follow same guidelines as one-dimensional ... • Notice how each row is grouped using

8/29/2015

25

Other Collection Classes

• Dictionary<Tkey, Tvalue> - has much of the sameDictionary<Tkey, Tvalue> has much of the same functionality as the Hashtable class– Generic class that provides a mapping from a set of keys to a

set of values

– Add( ) method

– Item property

– Reference and retrieve values from the collection using its– Reference and retrieve values from the collection using its Keys and Values properties

HINT: use this class instead of HashTable.

C# Programming: From Problem Analysis to Program Design 49

TempAgency Application Example

50

Figure 8-8 Problem specification for Manatee example

Page 26: 9781285096261 ch08 PPT - csuohio.educis.csuohio.edu/.../9781285096261_ch08_PPT_Handout.pdf · follow same guidelines as one-dimensional ... • Notice how each row is grouped using

8/29/2015

26

TempAgency Application Example (continued)

Table 8-3 Instance field members for the TempAgency class

C# Programming: From Problem Analysis to Program Design 51

TempAgency Application Example (continued)

C# Programming: From Problem Analysis to Program Design 52

Figure 8-9 Prototype

Page 27: 9781285096261 ch08 PPT - csuohio.educis.csuohio.edu/.../9781285096261_ch08_PPT_Handout.pdf · follow same guidelines as one-dimensional ... • Notice how each row is grouped using

8/29/2015

27

TempAgency Application Example (continued)

C# Programming: From Problem Analysis to Program Design 53

Figure 8-10 Class diagrams

TempAgency Application

Example (continued)

C# Programming: From Problem Analysis to Program Design 54

Figure 8-11 TempAgencyclass methods behavior

Page 28: 9781285096261 ch08 PPT - csuohio.educis.csuohio.edu/.../9781285096261_ch08_PPT_Handout.pdf · follow same guidelines as one-dimensional ... • Notice how each row is grouped using

8/29/2015

28

TempAgency Application Example (continued)

C# Programming: From Problem Analysis to Program Design 55

Figure 8-12 TempAgency application outputReview TempAgency

Example

Coding Standards

• Guidelines for Naming CollectionsGuidelines for Naming Collections

– Singular noun

– Camel case

• Advanced Array Suggestions

C# Programming: From Problem Analysis to Program Design 56

Page 29: 9781285096261 ch08 PPT - csuohio.educis.csuohio.edu/.../9781285096261_ch08_PPT_Handout.pdf · follow same guidelines as one-dimensional ... • Notice how each row is grouped using

8/29/2015

29

Resources

An Extensive Examination of Data Structures –An Extensive Examination of Data Structures http://msdn.microsoft.com/en-us/library/aa289148(VS.71).aspx

MSDN C# Data Structures series –http://www.andrewconnell.com/blog/archive/2004/02/17/262.aspx

C# String Tutorial –http://csharp.net-informations.com/string/csharp_string_tutorial.htm

M ltidi i l AMultidimensional Arrays –http://www.functionx.com/csharp/Lesson23.htm

C# Programming: From Problem Analysis to Program Design 57

Chapter Summary• Multidimensional array declaration

– Compile-time initializationCompile time initialization – Accessing elements

• ArrayList class members• String class members• Other Collection classes

– BitArray– HashTable

C# Programming: From Problem Analysis to Program Design 58

– Queue– Stack– List– HashSet

Page 30: 9781285096261 ch08 PPT - csuohio.educis.csuohio.edu/.../9781285096261_ch08_PPT_Handout.pdf · follow same guidelines as one-dimensional ... • Notice how each row is grouped using

8/29/2015

30

Appendix: Temp-Agency (our approach) pp.1

namespace ConsoleApplication1

{

//From Figure 8.8, Temp Agency Problem

class TempAgencyDemo

{

bli id M i ( t i [] )public void Main(string[] args)

{

//SalesPerson sp1 = new SalesPerson("Maria Macarena", 1000.00); //testing

SalesPerson sp1 = CreateSalesPersonObject();

sp1.CalculateFutureSales();

Console.WriteLine(sp1.ShowPersonData());

}//Main

59

// ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐

// Method: CreateSalesPersonObject()

// This method prompts the user to enter fullname and initial target amount,

// it returns a new SalesPerson object holding values collected from the user.

// Ob th t i t ti ll thi th d h t b i l d d i th

Appendix: Temp-Agency (our approach) pp.2

// Observe that intentionally this method has not been included in the 

// SalesPerson class. Instead it is part of the 'static' test program.

// ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐

private SalesPerson CreateSalesPersonObject()

{

Console.WriteLine("Temp Agency Demo ‐ Enter Person Name");

string fullName = Console.ReadLine();

string[] names = fullName.Split(' ');

Console.WriteLine("Enter {0}'s target amount ", names[0]);

int targetAmount = int.Parse(Console.ReadLine());

Console.WriteLine("target amount for {0} is {1}", names[0], targetAmount);

60

( g { } { } [ ] g )

return new SalesPerson(fullName, targetAmount);

}

}

}

Page 31: 9781285096261 ch08 PPT - csuohio.educis.csuohio.edu/.../9781285096261_ch08_PPT_Handout.pdf · follow same guidelines as one-dimensional ... • Notice how each row is grouped using

8/29/2015

31

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;

Appendix: Temp-Agency (our approach) pp.3

using System.Threading.Tasks;

namespace ConsoleApplication1{

class SalesPerson{

string personName;double[] sales;const int MONTHS = 4;

public SalesPerson(string nameValue, double firstTargetValue){

61

{

string[] nameParts = nameValue.Split(' ');personName = nameParts[1] + ", " + nameParts[0];sales = new double[MONTHS];sales[0] = firstTargetValue;

}

public void CalculateFutureSales(){

double pct = 0.05;for (int i = 1; i < MONTHS; i++){

Appendix: Temp-Agency (our approach) pp.4

{sales[i] = sales[i ‐ 1] * (1 + pct);

}}

public string ShowPersonData(){

string result = String.Format("{0:20s}", personName); ;for (int i = 0; i < MONTHS; i++){

string currencyValue = String.Format("{0,15:C}", sales[i] );

62

if (i == 0)result += " " + currencyValue;

elseresult += ", " + currencyValue;

}return result;

}}

}