O
O
onixela2016-10-31 21:04:36
Mathematics
onixela, 2016-10-31 21:04:36

How to make an entire program repeat on demand (C#)?

It is required to ask the user if he wants to repeat the test he wrote earlier and, if the answer is yes, start the test again, otherwise finish the job.
It seems like I need to wrap all the code in do while, but I'm doing something wrong.
here is my non-working variant:
string answer;
string yes = "yes";
do
{
"Some code"
Console.WriteLine("Would you like to repeat the test? (Yes/No)");
answer = Convert.ToString(Console.ReadLine());
} while (answer == yes) ;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Nemiro, 2016-10-31
@onixela

If the user's answer is different from yes , then the loop will end.
It is better to check the answer in a case-insensitive way, perhaps the problem is this:

string answer;
string yes = "yes"; 
// из yes лучше сделать константу, чтобы в этом был смысл :)
// const string yes = "yes"; 
// либо массив - это позволит проверять разные варианты ответов
string[] yesVariants = { "yes", "y", "true", "да", "еще бы", "только об этом и мечтаю" };
// или можно использовать регулярные выражения

do
{

  // любой код здесь

  Console.WriteLine("Желаете повторить тест?(Yes/No) ");
  answer = Console.ReadLine();

} while (answer.Equals(yes, StringComparison.OrdinalIgnoreCase));
// проверка по массиву ответов
// } while (yesVariants.Contains(answer, StringComparer.OrdinalIgnoreCase));

56258ea1eb5a4826a05a07bf0beeddd8.gif

1
15432, 2016-10-31
@15432

But isn't the literal \n (newline) formed at the end of the input string?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question