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

Why would this code display error even when it shouldn't?

I am sort of new to programming and I cannot get this simple looking code to work
What I am trying to do is make a login system that works on an array so its easier to edit and add new people onto the list.

string[] UserCodes = { "admin", "testcode" }; //these are the arrays
string[] UserWords = { "123", "testword" };

public void Button_Clicked(object sender, EventArgs e)
{
    for (int i = 0; i < UserCodes.Length; i++)
        if (UserCode.Text.Equals(UserCodes[i])  && UserWord.Text.Equals(UserWords[i]))
        {
            Navigation.PushAsync(new HomePage());
        }
    for (int i = 0; i < UserCodes.Length; i++)    
        if (UserCode.Text != (UserCodes[i]) || UserWord.Text !=(UserWords[i]))
        {
            DisplayAlert("Something Went Wrong", "Incorrect Password or Username", "Try Again");
        }   
}                   // And this is the "main" code

I believe the main problem arises from the second part, where it displays an error, because if I don’t enter the password correctly it works as it should but if I do enter correctly It sends me to the home page while still displaying the error. I have tried using else if, and i tried to use (!command.Equals(Array[i])). I am extremely confused as to why its acting this way.

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 :

Step through this code in the debugger. If you type in a correct UserCode and UserWord you will call Navigation.PushAsync(new HomePage())… and then keep going.

You next check if any UserWord or UserCode is not what you typed, and it will be, then show your error message.

You probably want to call return after Navigation.PushAsync(new HomePage()), or skip over the second for statement.

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