If operator doesn't work C #

I'm not sure if I am really tired and am missing something obvious or something wrong with my program. Basically the condition of the if statement doesn't work.

public bool check(string nextvaluebinary)
        {
            bool test = true;

            for (int i = -1; i < 8; ++i)
            {
                i++;
                System.Console.WriteLine(nextvaluebinary[i] + " " + nextvaluebinary[i + 1]);
                if (nextvaluebinary[i] == 1)
                {
                    System.Console.WriteLine("Activated");
                    if (nextvaluebinary[i + 1] == 0)
                    {
                        test = false;
                        System.Console.WriteLine("false");
                    }
                }
                else
                {
                    test = true;
                }

                if (test == false)
                {
                    break;
                }
            }

            return test;
        }

      

I am passing the string 0001010110 and im getting the output:

0 0
0 1
0 1
0 1
1 0

      

but not "activated" or "false", although the last value is "1 0". Sorry again if this is a stupid question and any insight or help would be greatly appreciated.

+3


source to share


3 answers


You are comparing char to int. The validation you are trying has a completely different meaning than what you are trying to accomplish. You need to either check if it is "1" or cast char to int so that you can do numeric comparison.



if (nextvaluebinary[i] == '1')

      

+9


source


Since it nextvaluebinary

is String

, this comparison will only be performed if this string has a null character, that is '\0'

:

if (nextvaluebinary[i + 1] == 0)

      



It looks like you are looking for the null character of a digit, so you should write

if (nextvaluebinary[i + 1] == '0')

      

+2


source


Equality is used with char to int. So the char code will be used.

Use this

    public static bool check(string nextvaluebinary)
    {
        bool test = true;

        for (int i = -1; i < 8; ++i)
        {
            i++;
            System.Console.WriteLine(nextvaluebinary[i] + " " + nextvaluebinary[i + 1]);
            if (nextvaluebinary[i] == '1')
            {
                System.Console.WriteLine("Activated");
                if (nextvaluebinary[i + 1] == '0')
                {
                    test = false;
                    System.Console.WriteLine("false");
                }
            }
            else
            {
                test = true;
            }

            if (test == false)
            {
                break;
            }
        }

        return test;
    }

      

0


source







All Articles