简体   繁体   中英

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


        }
    }
}

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.");
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM