public static Product[] LoadItems()
{
//method to return array contents of vending machine
return new Product[] {
new Product() { name = "Cheese", price = 2.0M },
new Product() { name = "Salami", price = 1.5M },
new Product() { name = "Kitkat", price = 1.0M },
new Product() { name = "Fanta", price = 1.8M },
new Product() { name = "Sharp hamburger", price = 4.3M },
new Product() { name = "Coconut water", price = 0.8M },
new Product() { name = "Crackers", price = 2.0M },
new Product() { name = "Orange juice", price = 0.75M },
new Product() { name = "Water", price = 0.6M }
};
}
static void Main(string[] args)
{
//creates array named machine using LoadItems
Product[] machine = LoadItems();
Console.WriteLine("Welcome to the vending machine. The products available are:");
for (int i = 0; i < machine.Length; i )
{
Console.WriteLine(machine[i]);
}
}
I would like to display the items and prices, however I am unsure on how to do this.
I believe it may be an error with my formatting of Console.WriteLine(machine[i]);
CodePudding user response:
Try this code
Product[] machine = LoadItems();
Console.WriteLine("Welcome to the vending machine. The products available are:");
for (int i = 0; i < machine.Length; i )
{
Console.WriteLine("Name: " machine[i].name " Price: " machine[i].price);
}
CodePudding user response:
When you try to output an object, it has to be converted to a string. This is done via the ToString()
method, which you can override.
For example
class Product
{
public override string ToString()
{
return string.Format("Name: {0} Price: {1:0.00}", this.name, this.price);
}
}
After you've done this, the console will display a more friendly string when you output the product.