Parse Player Choice

πŸ“– Instructions#

playerChoice currently holds the player’s input as text. But later in the game we’ll need to compare it to numbers β€” and text and numbers are different data types. You can’t compare them directly.

To fix this, we need to parse the string into an integer. Parsing means reading a piece of text and converting it into another type.

string raw = Console.ReadLine();
int number = int.Parse(raw);

int.Parse() takes a string and returns an integer. The string must contain a valid whole number β€” otherwise the program will crash.

🧠 Recall

πŸŽ“ Learn More

βœ… What to Do#

Rename the existing playerChoice variable to input, then declare a new integer variable named playerChoice and assign it the parsed value of input.

🎯 Expected Outcome#

The output looks exactly the same as before. The difference is that playerChoice is now a number, ready to be used in comparisons later.

Welcome to Odds and Evens!
Choose 1 for Odds or 2 for Evens:
1

πŸ’‘ Hints#

Hint 1

You need two variables now instead of one β€” one to hold the raw text, one to hold the parsed number.

Hint 2

The raw text variable should be a string type. The parsed number variable should be an integer type.

Hint 3

Pass the string variable into int.Parse() and assign the result to the integer variable.

⚠️ Common Mistakes#

Passing a literal value instead of the variable

Passing a hard-coded value to the parse function ignores what the player actually typed. Always pass the variable that holds the player’s input.

Keeping the same variable name for both

You can’t declare two variables with the same name in the same scope. Rename the string variable to input first, then declare the integer variable as playerChoice.

Declaring the parsed variable with the wrong type

The parse function returns an integer, so the variable that receives it must be declared as int β€” not string.

Entering non-numeric input while testing

If you type something like abc when running the program, int.Parse() will crash. For now assume the player always enters a valid number β€” handling invalid input comes later.

πŸ™ˆ Solution#

Tried, you must, before reveal the solution you may.

Program.csChanges

  // Player chooses to play with odds or evens.
  Console.WriteLine("Choose 1 for Odds or 2 for Evens:");
- string playerChoice = Console.ReadLine();
+ string input = Console.ReadLine();
+ int playerChoice = int.Parse(input);

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);

(...)