Exercise – Create nested decision logic with if, else if, and else
In the previous unit, you used multiple if
statements to implement the rules of a game. However, at the end of the unit, you noticed that more expressive if
statements are needed to fix a subtle bug in your code.
In this exercise, you’ll use if
, else
, and else if
statements to improve the branching options in your code and fix a logic bug.
Use if and else statements instead of two separate if statements
Instead of performing two checks to display the “You win!” or “Sorry, you lose” message, you’ll use the else
keyword.
- Ensure that your Program.cs code matches the following:c#Copy
Random dice = new Random(); int roll1 = dice.Next(1, 7); int roll2 = dice.Next(1, 7); int roll3 = dice.Next(1, 7); int total = roll1 + roll2 + roll3; Console.WriteLine($"Dice roll: {roll1} + {roll2} + {roll3} = {total}"); if ((roll1 == roll2) || (roll2 == roll3) || (roll1 == roll3)) { Console.WriteLine("You rolled doubles! +2 bonus to total!"); total += 2; } if ((roll1 == roll2) && (roll2 == roll3)) { Console.WriteLine("You rolled triples! +6 bonus to total!"); total += 6; } if (total >= 15) { Console.WriteLine("You win!"); } if (total < 15) { Console.WriteLine("Sorry, you lose."); }
This is the code that you completed in the previous unit.