Operator '==' cannot be applied to operands of type 'int' and 'string

拈花ヽ惹草 提交于 2019-12-01 13:39:22

问题


I'm in the middle of writing a program where I think of a number, and the computer guesses it. I'm trying to test it as I go along, but I keep getting an error I should'nt be. The error is the topic title. I used Int.Parse to convert my strings, but I don't know why I'm getting the error. I know it says '==' can't be used with integers, but everything I've seen online plus the slides from my class all use it, so I'm stuck. The code is incomplete and I'm not trying to get it to run yet, I just want to fix the problem. I appreciate any help a lot, thanks :D

class Program
{
    static void Main(string[] args)
    {
        Console.Write("Enter any number after 5 to start: ");
        int answer = int.Parse(Console.ReadLine());
        {
            Console.WriteLine("is it 3?");
            if (answer == "higher")

回答1:


You ask for a number, but you are trying to compare it to non-numeric data. Forget language semantics, how do you expect to compare a number to text? What does it mean to ask if a number like 3 is equal to "higher"?

The answer is that it is nonsensical; this is one reason why the language does not allow it.

int a = 1;
string b = "hello";

if (a == 1)       { /* This works; comparing an int to an int */ }
if (a == "hello") { /* Comparing an int to a string!? This does not work. */ }
if (b == 1)       { /* Also does not work -- comparing a string to an int. */ }
if (b == "hello") { /* Works -- comparing a string to a string. */ }

You can force the comparison to compile by converting your number to a string:

if (answer.ToString() == "higher")

But this condition will never be met because there is no int value that would convert to the text "hello". Any code inside of the if block would be guaranteed never to execute. You might as well write if (false).




回答2:


Why are you comparing an integer to a string? Higher is ONLY a string and cannot be turned into an integer which exclusively a number.

But I think what you might also want is ToString()

Usage:

int x = 5;
string y = x.ToString();
Console.WriteLine(y);


来源:https://stackoverflow.com/questions/26208564/operator-cannot-be-applied-to-operands-of-type-int-and-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!