Hello!
I am coding in c# and I am having trouble using boolean variables and if statements. The project I am working on is based on the users input, and the code should branch into two different options. However, I am struggling to understand how to take the users input to decide which path to take. Another problem I am having is with my if statements. After the user has inputed information and the code decides to take them down path 1 or path 2, it does not use the information correctly. Here is the bit of code I am talking about:
if (Hourly >= 100.00)
{
TotalPay = Hourly - (Hourly * 0.10);
FinalPay = TotalPay * 0.10;
NextPay = TotalPay - FinalPay;
}
else
{
TotalPay = Hourly;
FinalPay = TotalPay;
NextPay = TotalPay;
}
if (Hourly >= 50.00)
{
TotalPay = Hourly - (Hourly * 0.02);
FinalPay = TotalPay * 0.10;
NextPay = TotalPay - FinalPay;
}
if (Hourly < 100.00)
{
TotalPay = Hourly - (Hourly * 0.02);
FinalPay = TotalPay * 0.10;
NextPay = TotalPay - FinalPay;
}
if (Hourly < 50.00)
{
TotalPay = Hourly - (Hourly * 0.05);
FinalPay = TotalPay * 0.10;
NextPay = TotalPay - FinalPay;
}
Console.WriteLine(NextPay);
It keeps using the wrong if statement and I am not sure why. I have found the source of it, which is in the statement if (Hourly >=50.00). I am not for sure why it keeps overriding the if (Hourly >= 100.00) . I do know that it is technically correct in running because it is greater then or equal to 50, but I would think it would take precedent and use the 100.00. Any help would be appreciated!
Stacking 'if' one over the other will result in this problem.
After one 'if', use 'else' if in the next if. I also used to make the same mistake. Here, I have made the correction. And else should be in the end always. Also, you can combine boolean expressions which have the same code. Try to keep the if conditions in order. Look athe modified code, you will understand.
if (Hourly < 50.00)
{
TotalPay = Hourly - (Hourly * 0.05);
FinalPay = TotalPay * 0.10;
NextPay = TotalPay - FinalPay;
}
else if (Hourly > 50.00 && Hourly < 100.00)
{
TotalPay = Hourly - (Hourly * 0.02);
FinalPay = TotalPay * 0.10;
NextPay = TotalPay - FinalPay;
}
if (Hourly >= 100.00)
{
TotalPay = Hourly - (Hourly * 0.10);
FinalPay = TotalPay * 0.10;
NextPay = TotalPay - FinalPay;
}
else
{
TotalPay = Hourly;
FinalPay = TotalPay;
NextPay = TotalPay;
}
Console.WriteLine(NextPay);
Get Answers For Free
Most questions answered within 1 hours.