user2509901
user2509901

Reputation:

Nested While Statement not working

I have a console program that draws a shape based on length and breadth entered by the user. When this is done. I want to ask the user if he wants to draw another shape and if yes. It should restart the program. Also, when the user is asked to enter Y for Yes or N for No. I want to ensure that the user cannot outside these two letters. I am currently using this in my main method.

DrawShape mn = new DrawShape();
mn.ans = "y";
while (mn.ans.ToLower() == "y")
{
    try
    {
        mn.Lenght();
        Console.WriteLine();
        mn.Breadth();
        Console.WriteLine();
        mn.Draw();
        Console.WriteLine("\n");
        mn.Remark();
        Console.WriteLine("\n\nDO YOU WANT TO REDRAW A SHAPE? \nPRESS Y - YES or N - NO");
        mn.ans = Console.ReadLine();
        Console.WriteLine();
        while (mn.ans.ToLower() != "y" || mn.ans.ToLower() != "n")
        {
            Console.WriteLine("\nPLEASE PRESS Y - YES or N - NO");
            mn.ans = Console.ReadLine();
        }
    }
    catch (Exception e)
    {
        Console.WriteLine("\n" + e.Message);
        Console.WriteLine();
    }
}

This doesn't work as this is the output i get

output

This shows that whatever i input, the error message is still shown.

Please what am i doing wrong?

Upvotes: 2

Views: 80

Answers (1)

King King
King King

Reputation: 63377

You use the wrong operator, use && instead of ||:

while (mn.ans.ToLower() != "y" && mn.ans.ToLower() != "n") {
        Console.WriteLine("\nPLEASE PRESS Y - YES or N - NO");
        mn.ans = Console.ReadLine();
}

Or this:

while (!(mn.ans.ToLower() == "y" || mn.ans.ToLower() == "n")) {
        Console.WriteLine("\nPLEASE PRESS Y - YES or N - NO");
        mn.ans = Console.ReadLine();
}

NOTE: You should store mn.ans.ToLower() to a variable to avoid duplicated code. You can also try using Equals method which supports comparing string case-insensitively via the StringComparison.CurrentCultureIgnoreCase passed in.

Upvotes: 4

Related Questions