Click here to Skip to main content
15,888,610 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I'm Matt and I'm kinda new to c#. I've been coding with GML(Game Making Language) and Python. I wanted to learn a new coding language, so I started learning c# less than a week ago.

I've learnt my c# from a tutorial series(Bob Tabor on MSDN) and I wanted to try and make my own program - a Lottery Game! If you guess the randomly generated number between 1 and 3 you win the lottery!

The problem I get so far it says Operator '==' cannot be applied to operands of type 'int' and 'string'. I know it is with converting the userValue to an integer, but I don't know how to do it D:

My code is below.

What I have tried:

Random random = new Random(); // Importing the random function
           int number = random.Next(1,3);

           // Stating the game name
           Console.WriteLine("LOTTERY GAME");
           Console.WriteLine("--------------");
           Console.WriteLine("Pick a number: 1, 2 or 3.");
           string userValue = Console.ReadLine();

           string message = (userValue == number) ? "You won the Lottery!" : "Sorry, you didn't get the right number. Better luck next time!";
           Console.WriteLine("{0} The number you typed was {1}.", message, userValue);
           Console.ReadLine();
Posted
Updated 8-Dec-17 9:45am
Comments
Richard MacCutchan 8-Dec-17 16:29pm    
You cannot compare a string to an int, they are totally different types. You need to study the basics of C#.

1 solution

Use int.TryParse[^] to attempt to convert the string to an int. You'll also need to account for cases where the user doesn't type a valid number.
C#
string userText = Console.ReadLine();

int userValue;
while (!int.TryParse(userText, out userValue))
{
    Console.WriteLine("Sorry, I didn't understand that.");
    Console.WriteLine("Pick a number: 1, 2 or 3.");
    userText = Console.ReadLine();
}

string message = (userValue == number) ? "You won the Lottery!" : "Sorry, you didn't get the right number. Better luck next time!";
Console.WriteLine("{0} The number you typed was {1}.", message, userValue);
Console.ReadLine();
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900