New to C# (only coding for a week so far) trying to create a practice program. Can't seem to get the data I want stored in 'price1' and 'price2'. Error is CS0165 Use of unassigned local variable 'price1' and 'price2'.
I've tried moving lines of code around and adding in a return command, but I can't quite seem to figure it out.
Console.Write("What grocery are you buying: ");
string product1 = Console.ReadLine();
Console.Write("How many are you buying: ");
int quantity1 = Convert.ToInt32(Console.ReadLine());
double price1;
if (product1 == "Steak")
{
price1 = Convert.ToDouble(steak.price * quantity1);
}
if (product1 == "Cheerios")
{
price1 = Convert.ToDouble(cheerios.price * quantity1);
}
if (product1 == "Pepsi")
{
price1 = Convert.ToDouble(pepsi.price * quantity1);
}
if (product1 == "Celeste Pizza")
{
price1 = Convert.ToDouble(celeste.price * quantity1);
}
Console.Write("What second grocery are you buying: ");
string product2 = Console.ReadLine();
Console.Write("How many are you buying: ");
int quantity2 = Convert.ToInt32(Console.ReadLine());
double price2;
if (product2 == "Steak")
{
price2 = Convert.ToDouble(steak.price * quantity2);
}
if (product1 == "Cheerios")
{
price2 = Convert.ToDouble(cheerios.price * quantity2);
}
if (product1 == "Pepsi")
{
price2 = Convert.ToDouble(pepsi.price * quantity2);
}
if (product1 == "Celeste Pizza")
{
price2 = Convert.ToDouble(celeste.price * quantity2);
}
Console.WriteLine(price1 + price2);
Trying to get data stored in 'price1' and 'price2' so I can add them together at the end. Sorry if I'm getting any terminology wrong here.
The problem is that if
product1does not equal any of the values in yourifstatements, then none of those sections will ever run, and so in theory there is a danger thatprice1might never be given a value. And it can't use something which doesn't have a value to add it to something else. That's what the compiler is complaining about. You need to giveprice1a default value when you first declare it, as a fallback option in case the user enters something which is not one of the four expected product names.Is probably ok for this scenario, but you can choose whatever value you think is best, as long as there is some kind of value.
You will have the exact same issue with
price2as well.