Click here to Skip to main content
15,886,799 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello all I have a loop in a console application. I am using a while loop and grabbing the users input. I am checking the input and if the input isn’t valid I would like to go to the beginning so they can try again. Currently once they are wrong I am stuck at the end it doesn’t matter if they enter the right input again im stuck at the end

C#
for(int i = 0; i < answers.Length; i++)
            {
                Console.WriteLine("Question " + (i + 1) + ": ");
                string input = Console.ReadLine();
                
                if(char.TryParse(input, out char inserted))
                {
                    answers[i] = inserted;

                    // Validate the answer.
                    while (!Valid(answers[i]))
                    {
                        Console.WriteLine("ERROR: Valid answers are A, B, C, or D.");
                        Console.Write("Question " + (i + 1) + ": ");
                        input = Console.ReadLine();
                        if(char.TryParse(input, out char userChar))
                        {
                            answers[i] = inserted;
                        }
                    }
                }
            }


What I have tried:

Moving stuff around and trying to exit the loop but stuck at the end
Posted
Updated 18-Dec-18 21:03pm

1 solution

Your following condition seems to be culprit. You are using inserted variable while you are taking input and putting it in userChar.

Either use inserted at both places or change your while condition. Try the following:

C#
if(char.TryParse(input, out char userChar))
{
     answers[i] = userChar; // note this 
}


or you need to use inserted in your TryParse method call:

C#
if(char.TryParse(input, out char inserted))
{
     answers[i] = inserted;
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900