Reputation: 11
Ok so my question is this, I currently have 3 possible answers: yes, no, and everything else. I want my program to write "Pardon me?" until I answer yes or no... I'm new to using c# and still learning so please as simple as possible. Thank you
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Pitalica
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Kvisko");
Console.WriteLine("\"Hello Traveller!!\" says a man. \"What's your name?\"");
string playerName = Console.ReadLine();
Console.WriteLine("\"Hi " + playerName + ", welcome to the beautiful city of Osijek!\nI would like to give you a tour of our little town, but I don't have time to do so right now.\nI need to go to class.\"");
Console.WriteLine("He looks at you with your backpack on your back.\"But I could show you later if you're up to?\"");
string answer1 = Console.ReadLine();
if (answer1 == "yes")
Console.WriteLine("\"We have a deal, " + playerName + "!\"");
else if (answer1 == "no")
Console.WriteLine("\"Your loss," + playerName + "...\"");
else
{
Console.WriteLine("Pardon me?");
}
Console.WriteLine("After some time...");
}
}
}
Upvotes: 1
Views: 73
Reputation: 186803
Technically, you can implement any loop, but I suggest while
...
string answer1 = Console.ReadLine();
while (answer1 != "yes" && answer1 != "no") {
Console.WriteLine("Pardon me?");
answer1 = Console.ReadLine();
}
...
Just keep asking while answer1
is not a correct one.
Edit: As Hogan suggested in the comment, we should be nice to user: let he/she enter YES/no in any register with leading and trailing white spaces:
...
// with Trim() and ToUpper() all "Yes", " yes", "YES " are OK
string answer1 = Console.ReadLine().Trim().ToUpper();
while (answer1 != "YES" && answer1 != "NO") {
Console.WriteLine("Pardon me?");
answer1 = Console.ReadLine().Trim().ToUpper();
}
...
Edit 2: to exit the program (see an additional question in the comments), just return from the Main
:
...
if (answer1 == "NO") {
Console.WriteLine("Your loss");
return; // return from Main will exit the program
}
Upvotes: 7