Parse Player Choice

πŸ“– Instructions#

Right now, playerChoice holds the value the player typed β€” but it’s stored as a string . That means the program sees it as text, not as a number.

string playerChoice = Console.ReadLine();

That matters because later we’ll need to do things with this value that only work with numbers, like comparing it to 1 or 2. Text and numbers are different types , and mixing them up leads to problems.

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.

In C#, int.Parse() does exactly that. You pass it a string, and it gives back an integer:

int score = int.Parse("1");
  • int.Parse("1") converts the text "1" into the number 1
  • score now holds an integer, ready to be used as a number

πŸŽ“ Learn More

βœ… What to Do#

  • Rename the existing playerChoice variable to input.
  • Declare a new int variable named playerChoice and assign it the result of parsing input.
  • Run the program.

If the player types something that isn’t a number β€” like abc β€” int.Parse() will crash the program. For now, assume the player always enters a valid number. Handling invalid input is something you’ll learn to do later.

🎯 Expected Outcome#

The program should behave exactly as before β€” no visible change in the console output. The difference is that the player’s choice is now stored as a number.

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

Not all progress is visible. Changing the type of a variable doesn’t produce output, but it is an essential step for what comes next.

πŸ’‘ Hints#

Hint 1

Find the line with string playerChoice = Console.ReadLine();. That’s the one you need to update.

Hint 2

Split it into two lines: one that reads the input into a string variable, and one that parses it into an int variable.

Hint 3

Use int.Parse() and pass the string variable to it. Assign the result to a new variable of type int.

πŸ™ˆ 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);

(...)