Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to create an "if" statement in c# so that if a string is bigger than a int it displays a message

Tags:

c#

I'm creating a random number guessing game so that a random number is generated and the user has to guess the number, if they guess below the number then they get to guess again, the same if they guess above until they guess the right number. P.S I also tried int.Parse to change the user inputted string into a number but still got the "Operator "<" can not be applied to operands of type 'string' and 'int'

I'm Trying to create an "if" statement in c# so that if a string (the user inputed number) is bigger than a int (the randomly generated number) it tells them to guess again. but as described above I get an error when using the 'less than' 'more than' symbols.

Thankyou in advance.

using System;

namespace randomNumberGenerator
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            Random random = new Random ();
            int randomNumber = random.Next (0, 100);

            Console.WriteLine ("Guess The Number I Am Thinking");
            string usernumber = Console.ReadLine ();

            int.Parse (usernumber);

            if (usernumber < randomNumber)
                Console.WriteLine ("No");
        }
    }
}
like image 649
EyyJP Avatar asked Nov 30 '25 07:11

EyyJP


2 Answers

int.Parse (usernumber); would return you an integer value, It will not modify the string usernumber or change its type to integer. You need

int number;
number = int.Parse(usernumber);
if(number < randomNumber)
{
    Console.WriteLine("No");
}

It is also better if you use int.TryParse which would not throw an exception in case, where user enters a non numeric string value.

like image 118
Habib Avatar answered Dec 01 '25 20:12

Habib


Parse returns an int, but does not modify the variable you passed to it. So you need a new variable

var number = int.Parse (usernumber);
if (number < randomNumber)

Your error basically says that you can't compare variables of different types (string and int in this case). The compiler doesn't know if your string can actually be interpreted as a number.

You could also use TryParse,

int number;
var validNumber = int.TryParse(usernumber, out number);

if (!validNumber)
{
    Console.WriteLine("Please choose a number. Bye...");
    return;
}

if (number < randomNumber)
    Console.WriteLine("No");
like image 31
mihai Avatar answered Dec 01 '25 20:12

mihai