-2

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.

Anthony P
  • 31
  • 2
  • 9
  • 1
    I think you need to step back and ask what you wanted that code to do.. you create a variable gold for the for loop, you dont set a starting value. you then ask if its <=10, and if its not +1, if gold is 10 bum out of the loop, otherwise you have x gold peice – BugFinder Apr 04 '17 at 10:33
  • 1
    Your best friend here is a debugger and the F10 key. – xanatos Apr 04 '17 at 10:33
  • "I am receiving an error", what error? Do you get a compiler or a runtime exception? If so, what does the exception message say? – PJvG Apr 06 '17 at 06:50
  • @EpicKip That would be appreciated. – Anthony P Apr 06 '17 at 07:48
  • @AnthonyP Re open your question i cant post it as comment – EpicKip Apr 06 '17 at 07:49

1 Answers1

2

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.

Equalsk
  • 7,954
  • 2
  • 41
  • 67