Предлагаю следующий код:
// char: we actually input a single character, not string
char input = '\0'; // initialize to make compiler happy
// keep on asking until success
while (true) {
Console.WriteLine("Enter a, b, c or d:");
// ReadKey: We want a single character, not a string
input = Console.ReadKey();
// input is valid if it's in ['a'..'d'] range
if (input >= 'a' && input <= 'd') {
Console.WriteLine("Success");
break;
}
Console.WriteLine("Try again");
}
Редактировать : в обобщенном случае (см. Комментарий Adriani6 ниже) код будет немного более сложным. Я предполагаю, что основной проблемой является своего рода вопросник , как
Compute 2 x 2 = ?
a. 3
b. 4
c. 5
d. 0
Enter a, b, c or d:
именно поэтому я ожидаю, что действительный input
должен когда-либо находиться в некотором диапазоне ('a'..'d'
в приведенном выше примере), который я сохранил.
char from = 'a';
char upto = 'd';
// char: we actually input a single character, not string
char input = '\0'; // initialize to make compiler happy
// Building a title is, probably, the only complex thing (Linq)
string title =
$"Enter {string.Join(", ", Enumerable.Range(from, upto - from).Select(c => (char) c))} or {upto}:";
// keep on asking until success
while (true) {
Console.WriteLine(title);
// ReadKey: We want a single character, not a string
input = Console.ReadKey();
// Uncomment if we want a quit without choice, say, on Escape
//if (input == 27) { // or (input == 'q') if we want to quit on q
// input = '\0';
//
// break;
//}
// input is valid if it's in [from..upto] range
if (input >= from && input <= upto) {
Console.WriteLine("Success");
break;
}
Console.WriteLine("Try again");
}