Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# Returning Wrong Integer Value

i am trying to return an index based on the input of an user, the input is 2 characters only, like, a1, b2, c3…

public int returnInt(string x)
        {
            if (x == "a")
                return 0;
            else if (x == "b")
                return 1;
            else if (x == "c")
                return 2;
            else if (x == "d")
                return 3;
            else if (x == "e")
                return 4;
            else if (x == "f")
                return 5;
            else if (x == "g")
                return 6;
            else if (x == "h")
                return 7;
            else if (x == "1")
                return 0;
            else if (x == "2")
                return 1;
            else if (x == "3")
                return 2;
            else if (x == "4")
                return 3;
            else if (x == "5")
                return 4;
            else if (x == "6")
                return 5;
            else if (x == "7")
                return 6;
            else if (x == "8")
                return 7;
            return 0;
        }

And this is where i use the method:

var toMove = myButtonArray[returnInt(totxt.Text.Substring(0)), returnInt(totxt.Text.Substring(1))];

the method works fine for the second substring, but it doesn’t work for the first substring(0). Can anyone help me about this? When I type a1, program should return to 1 and 1 but it only returns 0 for the first substring.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Since your input string is always 2 characters only, and you want to use them as index for your 2-d array, you need to change your code to below:

var toMove = myButtonArray[returnInt(totxt.Text.Substring(0,1)), 
                           returnInt(totxt.Text.Substring(1,1))];

This way you are saying to String.Substring function to return 1 character at a time, and mentioning the start index as first input argument.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading