I am trying to make a small practice app, where user is asked their name, if its "joni" then there is a reply with YES or EXIT question. if User types YES it loops to asking question again, if user types EXIT it stops.
My problem is, how to make loop of asking YES or EXIT question if the user types different thing?
for example user types NO, so it will be asked again PLEASE TYPE YES or EXIT. But in my app it just exits if user types different thing than YES.
string? myValue;
do
{
Console.Write("Hey whats ur name?: ");
string? myName = Console.ReadLine();
if (myName == "joni")
{
Console.Write("Hey joni! Do you want to conitnue? YES or EXIT: ");
}
else
{
Console.Write("Hey student! Do you want to conitnue? YES or EXIT: ");
}
myValue = Console.ReadLine();
} while (myValue.ToLower() == "yes");
if (myValue.ToLower() == "exit")
{
Console.WriteLine("THANKS FOR USING MY APP!");
}
Console.ReadLine();
CodePudding user response:
I developed the menu() function to solve this problem. If the accepted entries are incorrect, the program prompts the user to enter a new menu value.
public static bool menu()
{
string? myValue;
do{
Console.WriteLine("Your Chooice: ");
myValue = Console.ReadLine();
} while (!(myValue.ToLower().Equals("yes") || myValue.ToLower().Equals("exit")));
if (myValue.ToLower() == "yes")
return true;
Console.WriteLine("THANKS FOR USING MY APP!");
return false;
}
The menu() method can be used as follows:
static void Main(string[] args)
{
do{
Console.Write("Hey whats ur name?: ");
string? myName = Console.ReadLine();
Console.WriteLine("Name: {0}", myName);
} while (menu());
Console.ReadLine();
}
CodePudding user response:
One way:
myValue = Console.ReadLine();
while (myValue.ToLower() is not "yes" or not "exit")
{
Console.WriteLine("PLEASE TYPE YES or EXIT");
myValue = Console.ReadLine();
}
CodePudding user response:
do/while construct loop as long as the condition remains true. You set the condition as myValue equals to "yes". You therefore set the do/while to loop as long as myValue is "yes".
But myValue is never "yes".
Moreover, you test for "exit" outside the loop.
You have to check the condition and fix it by inverting the equality operator and including a test for "exit".
