|
Rangées et classes : Rangées primitives comme variables de membre |
|
Comme nous avons utilisé jusqu'ici, une rangée est principalement une variable. En tant que tel, elle peut être déclarée comme un champ. Pour créer un champ comme rangée, vous pouvez le déclarer comme une rangée normale dans le corps de la classe. Voici un exemple : class NumberCrunching
{
double[] number;
}
|
|
|
Comme n'importe quel champ, quand une rangée a été déclarée comme variable membre, il est rendu disponible à tous les autres membres de la même classe. Vous pouvez utiliser ce dispositif pour initialiser la rangée dans une méthode et laisser d'autres méthodes utiliser la variable initialisée. Ceci signifie également que vous ne devez pas passer la rangée comme argument ni la retourner explicitement d'une méthode. Après ou en déclarant une rangée, vous devez vous assurer de lui assigner la mémoire avant de l'utiliser. À la différence de C++, vous pouvez assigner la mémoire pour une rangée en la déclarant. Voici un exemple : class NumberCrunching
{
double[] number = new double[5];
}
Vous pouvez également assigner la mémoire pour un champ de rangée dans un constructeur de la classe. Voici un exemple : class NumberCrunching
{
double[] Number;
public NumberCrunching()
{
Number = new double[5];
}
}
Si vous projetez utiliser la rangée dès que le programme fonctionnera, vous pouvez l'initialiser en utilisant un constructeur ou une méthode que vous savez serait avant que la rangée puisse être utilisée. Voici un exemple : 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;
}
}
Rappelez vous que, après qu'une rangée soit faite champ, il peut être utilisé par n'importe quel autre membre de la même classe. Basé sur ceci, vous pouvez utiliser un membre de la même classe pour demander les valeurs qui l'initialiseraient. Vous pouvez également utiliser une autre méthode pour explorer la rangée. Voici un exemple : using System;
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();
}
}
|
|
|
using System;
namespace IceScream3
{
// This class is used to create an ice scream
// And to process an order
sealed class IceScream
{
// This is the base price of an ice scream
// Optional values may be added to it
public const decimal BasePrice = 1.55M;
// These arrays are used to build
// the components of various ice screams
// 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 scream order
private int Scoops;
private decimal TotalPrice;
// This default constructor is the common place
// for us to initialize the array
public IceScream()
{
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 Scream Vending Machine");
// Let the user select the components of the ice scream
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 scream
TotalPrice = BasePrice + PriceScoop + PriceIngredient;
// Create the ice scream...
// 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 Scream 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 IceScream3
{
class Program
{
static int Main(string[] args)
{
IceScream ic = new IceScream();
ic.ProcessAnOrder();
return 0;
}
}
}
|
Ice Scream 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 Scream Order Flavor: Chocolate Chip Container: Cup Ingredient: No Ingredient Scoops: 2 Total Price: $2.60 Press any key to continue . . . |
|
Dans les leçons précédentes, nous avons utilisé les techniques traditionnelles pour localiser chaque article dans une rangée. Voici un exemple : 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;
}
}
Pour scanner une liste, le langage C# fournit deux mot-clé, foreach et in, avec la syntaxe suivante : foreach (type identifier in expression) statement les mots-clés foreach et in sont exigés. Le premier facteur de cette syntaxe, type, doit être un type de données (int, short, byte, double, etc.) ou le nom d'une classe qui existe dans le langage ou que vous avez créé. Le facteur identifier est un nom que vous indiquez pour représenter un article de la collection. Le facteur expression est le nom de la rangée ou de la collection. Le rapport à exécuter tandis que la liste est scannée est le facteur statement dans notre syntaxe. Voici un exemple : 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;
}
}
Ceci produirait : Employees Records Employee Name: Joan Fuller Employee Name: Barbara Boxen Employee Name: Paul Kumar Employee Name: Bertrand Entire |
|
|
||
| Précédent | Copyright © 2007, Yevol | Suivant |
|
|
||