Reputation: 15
I'm trying to make a program in which values increase as a button is pressed, and the progress is shown in a progress bar. The min is 0 and the max is 100 and I coded it so that if the value reaches above 100, make the value equal 100. However, it keeps going over 100 and giving me an error. I'm new to programming and I'm not sure where my error is.
if (happyLevel < 100)
{
happyLevel = happyLevel + 4;
}
else if (happyLevel > 100)
{
happyLevel = 100;
}
if (hungryLevel < 100)
{
hungryLevel = hungryLevel + 4;
}
else if (hungryLevel > 100)
{
hungryLevel = 100;
}
if (healthLevel < 100)
{
healthLevel = healthLevel + 4;
}
else if (healthLevel > 100)
{
healthLevel = 100;
}
Upvotes: 1
Views: 2268
Reputation: 19526
You don't want the else's in there. You have to consider what happens if adding 4 sets the level to more than 100:
if(happyLevel < 100)
happyLevel += 4;
if(happyLevel > 100)
happyLevel = 100;
As a side note, that code could also be replaced with:
happyLevel = Math.Min(100, happyLevel + 4);
Upvotes: 3
Reputation: 225164
You're checking using an else if
, which means that the + 4
could be incrementing any variable past 100 if you have a number higher than 96 within it. A quick way to fix it is to remove all the else
s before the if
s so you do the check no matter what.
Upvotes: 2
Reputation: 447
If one of the levels is 98 it will enter the first if statement related to it, get updated to 102, and not enter the else if. A quick and easy fix would be to change the else if's to just if.
Upvotes: 1