Arrays and Classes: Primitive Arrays as Member Variables |
|
As we have used so far, an array is primarily a variable. As such, it can be declared as a field. To create a field as an array, you can declare it like a normal array in the body of the class. Here is an example: using System; namespace Arithmetic { class NumberCrunching { double[] number; } } |
Practical Learning: Introducing Primitive Arrays as Fields of a Class |
Like any field, when an array has been declared as a member variable, it is made available to all the other members of the same class. You can use this feature to initialize the array in one method and let other methods use the initialized variable. This also means that you don't have to pass the array as argument nor do you have to explicitly return it from a method. After or when declaring an array, you must make sure you allocate memory for it prior to using. Unlike C++, you can allocate memory for an array when declaring it. Here is an example: using System; namespace Arithmetic { class NumberCrunching { double[] number = new double[5]; } } You can also allocate memory for an array field in a constructor of the class. Here is an example: using System; namespace Arithmetic { class NumberCrunching { double[] Number; public NumberCrunching() { Number = new double[5]; } } } If you plan to use the array as soon as the program is running, you can initialize it using a constructor or a method that you know would be before the array can be used. Here is an example: using System; namespace Arithmetic { class NumberCrunching { double[] Number = new double[5]; public NumberCrunching() { Number[0] = 12.44; Number[1] = 525.38; Number[2] = 6.28; Number[3] = 2448.32; Number[4] = 632.04; } } }
Remember that, after an array is made a field, it can be used by any other member of the same class. Based on this, you can use a member of the same class to request values that would initialize it. You can also use another method to explore the array. Here is an example: using System; namespace Arithmetic { class NumberCrunching { double[] Number = new double[5]; public NumberCrunching() { Number[0] = 12.44; Number[1] = 525.38; Number[2] = 6.28; Number[3] = 2448.32; Number[4] = 632.04; } public void DisplayNumber() { for (int i = 0; i < 5; i++) Console.WriteLine("Number {0}: {1}", i, Number[i]); } } class Program { static void Main() { NumberCrunching lstNumber = new NumberCrunching(); lstNumber.DisplayNumber(); } } } |
Practical Learning: Using Primitive Arrays in a Class |
using System; namespace IceCream3 { // This class is used to create an Ice Cream // And to process an order sealed class IceCream { // This is the base price of an Ice Cream // Optional values may be added to it public const decimal BasePrice = 1.55M; // These arrays are used to build // the components of various Ice Creams // In C#, we can allocate an array's memory in the body of the class private string[] Flavor = new string[10]; private string[] Container; private string[] Ingredient; // Additional factor used to process an Ice Cream order private int Scoops; private decimal TotalPrice; // This default constructor is the common place // for us to initialize the array public IceCream() { Flavor[0] = "Vanilla"; Flavor[1] = "Cream of Cocoa"; Flavor[2] = "Chocolate Chip"; Flavor[3] = "Organic Strawberry"; Flavor[4] = "Butter Pecan"; Flavor[5] = "Cherry Coke"; Flavor[6] = "Chocolate Brownies"; Flavor[7] = "Caramel Au Lait"; Flavor[8] = "Chunky Butter"; Flavor[9] = "Chocolate Cookie"; Ingredient = new string[4]; Ingredient[0] = "No Ingredient"; Ingredient[1] = "Peanuts"; Ingredient[2] = "M & M"; Ingredient[3] = "Cookies"; Container = new string[3]; Container[0] = "Cone"; Container[1] = "Cup"; Container[2] = "Bowl"; } // This method requests a flavor from the user and returns the choice public int ChooseFlavor() { int Choice = 0; // Make sure the user selects a valid number that represents a flavor... do { // In case the user types a symbol that is not a number try { Console.WriteLine("What type of flavor do you want?"); for (int i = 0; i < Flavor.Length; i++) Console.WriteLine("{0} - {1}", i + 1, Flavor[i]); Console.Write("Your Choice? "); Choice = int.Parse(Console.ReadLine()); } catch (FormatException) // display an appropriate message { Console.WriteLine("You must enter a valid number and no other character!"); } // If the user typed an invalid number out of the allowed range // let him or her know and provide another chance if (Choice < 1 || Choice > Flavor.Length) Console.WriteLine("Invalid Choice - Try Again!\n"); } while (Choice < 1 || Choice > Flavor.Length); // Return the numeric choice that the user made return Choice; } // This method allows the user to select a container public int ChooseContainer() { int Choice = 0; // Make sure the user selects a valid number that represents a container do { // If the user types a symbol that is not a number try { Console.WriteLine("What type of container do you want?"); for (int i = 0; i < Container.Length; i++) Console.WriteLine("{0} - {1}", i + 1, Container[i]); Console.Write("Your Choice? "); Choice = int.Parse(Console.ReadLine()); } catch (FormatException) // display an appropriate message { Console.WriteLine("You must enter a valid number and no other character!"); } // If the user typed an invalid number out of the allowed range // let him or her know and provide another chance if (Choice < 1 || Choice > Container.Length) Console.WriteLine("Invalid Choice - Try Again!"); } while (Choice < 1 || Choice > Container.Length); // Return the numeric choice that the user made return Choice; } public int ChooseIngredient() { int Choice = 0; do { try { Console.WriteLine("Do you want an ingredient or not"); for (int i = 0; i < Ingredient.Length; i++) Console.WriteLine("{0} - {1}", i + 1, Ingredient[i]); Console.Write("Your Choice? "); Choice = int.Parse(Console.ReadLine()); } catch (FormatException) { Console.WriteLine("You must enter a valid number and no other character!"); } if (Choice < 1 || Choice > Ingredient.Length) Console.WriteLine("Invalid Choice - Try Again!"); } while (Choice < 1 || Choice > Ingredient.Length); return Choice; } public void SpecifyNumberOfScoops() { do { try { Console.Write("How many scoops(1, 2, or 3)? "); Scoops = int.Parse(Console.ReadLine()); } catch (FormatException) { Console.WriteLine("You must enter a valid number and no other character!"); } if (Scoops < 1 || Scoops > 3) Console.WriteLine("Invalid Choice - Try Again!"); } while (Scoops < 1 || Scoops > 3); } // This method is used to process a customer order // It uses the values of the above methods public void ProcessAnOrder() { int ChoiceFlavor; int ChoiceContainer; int ChoiceIngredient; decimal PriceIngredient, PriceScoop; // Let the user know that this is a vending machine Console.WriteLine("Ice Cream Vending Machine"); // Let the user select the components of the Ice Cream ChoiceFlavor = ChooseFlavor(); ChoiceContainer = ChooseContainer(); ChoiceIngredient = ChooseIngredient(); SpecifyNumberOfScoops(); // If the user selects an ingredient instead of "No Ingredient", // add $0.50 to the order if (ChoiceIngredient == 2 || ChoiceIngredient == 3 || ChoiceIngredient == 4) PriceIngredient = 0.50M; else PriceIngredient = 0.00M; // Instead of multiplying a number scoops to a value, // We will use an incremental value depending on the number of scoops if (Scoops == 1) PriceScoop = 0.65M; else if (Scoops == 2) PriceScoop = 1.05M; else PriceScoop = 1.55M; // Calculate the total price of the Ice Cream TotalPrice = BasePrice + PriceScoop + PriceIngredient; // Create the Ice Cream... // And display a receipt to the user DisplayReceipt(ref ChoiceFlavor, ref ChoiceContainer, ref ChoiceIngredient); } // This method is used to display a receipt to the user public void DisplayReceipt(ref int Flv, ref int Cnt, ref int Igr) { Console.WriteLine("\nIce Cream Order"); Console.WriteLine("Flavor: {0}", Flavor[Flv - 1]); Console.WriteLine("Container: {0}", Container[Cnt - 1]); Console.WriteLine("Ingredient: {0}", Ingredient[Igr - 1]); Console.WriteLine("Scoops: {0}", Scoops); Console.WriteLine("Total Price: {0:C}\n", TotalPrice); } } } |
using System; namespace IceCream3 { class Program { static int Main(string[] args) { IceCream ic = new IceCream(); ic.ProcessAnOrder(); return 0; } } } |
Ice Cream Vending Machine What type of flavor do you want? 1 - Vanilla 2 - Cream of Cocoa 3 - Chocolate Chip 4 - Organic Strawberry 5 - Butter Pecan 6 - Cherry Coke 7 - Chocolate Brownies 8 - Caramel Au Lait 9 - Chunky Butter 10 - Chocolate Cookie Your Choice? 3 What type of container do you want? 1 - Cone 2 - Cup 3 - Bowl Your Choice? 2 Do you want an ingredient or not 1 - No Ingredient 2 - Peanuts 3 - M & M 4 - Cookies Your Choice? 1 How many scoops(1, 2, or 3)? 2 Ice Cream Order Flavor: Chocolate Chip Container: Cup Ingredient: No Ingredient Scoops: 2 Total Price: $2.60 Press any key to continue . . . |
In the previous lessons, we used the traditional techniques of locating each item in an array. Here is an example: class Exercise { static int Main() { string[] EmployeeName = new string[4]; EmployeeName[0] = "Joan Fuller"; EmployeeName[1] = "Barbara Boxen"; EmployeeName[2] = "Paul Kumar"; EmployeeName[3] = "Bertrand Entire"; Console.WriteLine("Employees Records"); Console.WriteLine("Employee 1: {0}", EmployeeName[0]); Console.WriteLine("Employee 2: {0}", EmployeeName[1]); Console.WriteLine("Employee 3: {0}", EmployeeName[2]); Console.WriteLine("Employee 4: {0}", EmployeeName[3]); return 0; } } To scan a list, the C# language provides two keyword, foreach and in, with the following syntax: foreach (type identifier in expression) statement The foreach and the in keywords are required. The first factor of this syntax, type, must be a data type (int, short, Byte, Double, etc) or the name of a class that either exists in the language or that you have created. The identifier factor is a name you specify to represent an item of the collection. The expression factor is the name of the array or collection. The statement to execute while the list is scanned is the statement factor in our syntax. Here is an example: class Exercise { static int Main() { string[] EmployeeName = new string[4]; EmployeeName[0] = "Joan Fuller"; EmployeeName[1] = "Barbara Boxen"; EmployeeName[2] = "Paul Kumar"; EmployeeName[3] = "Bertrand Entire"; Console.WriteLine("Employees Records"); foreach(string strName in EmployeeName) Console.WriteLine("Employee Name: {0}", strName); return 0; } } This would produce: Employees Records Employee Name: Joan Fuller Employee Name: Barbara Boxen Employee Name: Paul Kumar Employee Name: Bertrand Entire
|
|
||
Previous | Copyright © 2006-2007 FunctionX, Inc. | Next |
|