Reputation: 51
I am stuck on a c# issue where I cant get the while loop to end.
userValue is a string that is input earlier on in the program.
The string is formatted in DateTime, and the new input need to match the original userValue. I.E Confirming the the users original birth date.
I used a try / catch to determine if the input can be parsed to DateTime.
Currently it is just a constant loop, i'm trying to have the loop stop once the users birth date is verified.
string userValueTwo;
int stop = 0;
while (stop != 0)
{
Console.WriteLine("Please verify your birth date");
userValueTwo = Console.ReadLine();
try
{
DateTime birthdayTwo = DateTime.Parse(userValueTwo);
}
catch
{
Console.WriteLine("You did not enter a valid format.");
Console.ReadLine();
}
if (userValueTwo == userValue)
{
Console.WriteLine("Birth date confirmed.");
Console.ReadLine();
}
else
{
Console.WriteLine("Your birthday did not match our records. Please try again");
Console.ReadLine();
}
}
Upvotes: 3
Views: 7692
Reputation: 3845
You may use the break statement after the date is confirmed, although it is not reccommended.
Since you have already implemented a stop condition, just set stop to 1 after the date is confirmed and the while loop will not continue running.
Here's a better solution using a boolean:
bool stop = false;
while (!stop)
{
Console.WriteLine("Please verify your birth date");
userValueTwo = Console.ReadLine();
try
{
DateTime birthdayTwo = DateTime.Parse(userValueTwo);
}
catch
{
Console.WriteLine("You did not enter a valid format.");
Console.ReadLine();
}
if (userValueTwo == userValue)
{
Console.WriteLine("Birth date confirmed.");
Console.ReadLine();
stop = true;
}
else
{
Console.WriteLine("Your birthday did not match our records. Please try again");
Console.ReadLine();
}
}
Upvotes: 5
Reputation: 1
You have entered an infinite loop. Infinite loops typically when a user has not fulfilled one or more requirements for the code to "hop" on back out of the loop To exit a loop once a objective is fulfilled, use "break;", to escape out of that current loop. In cases where a loop is nested, this might need to happen more than once
Upvotes: 0