π Instructions#
Now we need the player to pick a number between 1 and 2. This is the same pattern you used to read the player’s choice β print a prompt, read the input, parse it into an integer.
π§ Recall
β What to Do#
Ask the player to choose a number between 1 and 2, read their input, and store the parsed result in an integer variable named playerNumber.
π― Expected Outcome#
Welcome to Odds and Evens!
Choose 1 for Odds or 2 for Evens:
1
You chose Odds.
Choose a number between 1 and 2:
1
π‘ Hints#
Hint 1
You’ve done this before. Look at the lines that handle the player’s choice β the structure is the same.
Hint 2
You need three things: a print statement for the prompt, a line to read the input, and a line to parse it.
Hint 3
The prompt message is Choose a number between 1 and 2:. The variable name is playerNumber.
β οΈ Common Mistakes#
Reusing playerChoice instead of declaring a new variable
playerChoice and playerNumber are two separate values. Declare a new variable for the player’s number β don’t overwrite the choice.
Forgetting to parse the input
Console.ReadLine() always returns a string. If you skip the parse step, playerNumber will be a string instead of an integer and comparisons later will fail.
Using the wrong variable name
The variable must be named playerNumber β it’s referenced by name in the lessons that follow. A different name will cause confusion when the code grows.
π Solution#
Tried, you must, before reveal the solution you may.
Program.csChanges
// Player enters a number between 1 and 2.
+ Console.WriteLine("Choose a number between 1 and 2:");
+ string rawNumber = Console.ReadLine();
+ int playerNumber = int.Parse(rawNumber);
Program.csFinal
Console.WriteLine("Welcome to Odds and Evens!");
// Player chooses to play with odds or evens.
Console.WriteLine("Choose 1 for Odds or 2 for Evens:");
string input = Console.ReadLine();
int playerChoice = int.Parse(input);
if (playerChoice == 1)
{
Console.WriteLine("You chose Odds.");
}
else
{
Console.WriteLine("You chose Evens.");
}
// Player enters a number between 1 and 2.
Console.WriteLine("Choose a number between 1 and 2:");
string rawNumber = Console.ReadLine();
int playerNumber = int.Parse(rawNumber);
(...)