Search code examples
c#visual-studioconsoleconsole-applicationtext-based

C# CS0136/CS0165 Errors Text-Based RPG


I'm currently making a test text-based RPG, I'm currently on the currency system and I am receiving an error. I'm not sure why.

for (int gold; gold <= 10; gold++){
if (gold == 10) {
break;
Console.WriteLine("You now have " + gold + " Gold Pieces"); }
}    

I'm not the most experienced coder ever, I'm still really new to C# so if you have anything that may help me get through this or even a better way to give the currency to the player, it would be appreciated.

Thank you.


Solution

  • You need to assign an initial value to gold and remove the break as it's unecessary:

    // Here I set 'gold' to 0
    for (int gold = 0; gold <= 10; gold++)
    {
        if (gold == 10) 
        {
            // Since `gold` == 10 then the loop will not iterate again anyway
            // so I removed the break
            Console.WriteLine("You now have " + gold + " Gold Pieces"); 
        }
    }
    

    I'm not sure of the reason for the loop since you don't do anything with the previous iterations, in this example at least you may as well just set gold to 10 straight away.