DEV_Beginner
DEV_Beginner

Reputation: 41

How do I use an if statement correctly?

I am not able to get this to run, because of the 1st line in the if statement. I am sure something needs to be converted, but I am not sure what.

My code:

using System;
using System.Collections.Generic;
using System.Text;

namespace xx
{
    class Program
    {
        static void Main(string[] args)
        {
           
           string userInput;
            Console.Write("what number do you choose: ");
            userInput = Console.ReadLine();

            if (userInput > 100)
                Console.WriteLine("I hate myself");
            else
                Console.WriteLine("I love myself");


        }
    }
}

Upvotes: 0

Views: 244

Answers (2)

Gishu
Gishu

Reputation: 136613

Try if (Int32.Parse(userInput) > 100)
You're trying to compare a string returned by Console.ReadLine() with an integer - that's why the compiler is cribbing.

Although a more robust approach .. now that I think of it would be to use Integer.TryParse

int parsedInt;
bool bResult = Int32.TryParse(stringToParse, out parsedInt)

bResult will be true only if the conversion/parse operation succeeded. This would handle rogue input. If successful, the out param contains the integer value you need.

Upvotes: 3

core
core

Reputation: 33059

userInput is a string, and you're trying to compare it to an int (100). The user input needs to be converted to an int first.

int i;

// TryParse() returns true/false depending on whether userInput is an int

if (int.TryParse(userInput, out i))
{
    if (i > 100)
    {
        Console.WriteLine("I hate myself");
    }
    else
    {
        Console.WriteLine("I love myself");
    }
}
else
{
    Console.WriteLine("Input was not a valid number.");
}

Upvotes: 18

Related Questions