在C#上再次运行该函数 [英] Running the function again on C#
问题描述
我有一个带有switch的简单代码.问题是在任何情况下完成或在默认情况下终止了代码.我想得到的是,完成后会问您想重复一次"这个问题,如果答案是Y,它将再次运行Main,如果它是N,则将终止,依此类推.我尝试过do ...同时又没有其他建议吗?
I have this simple code with switch. The thing is that after any case completed or after default the code is terminated. What I want to get that after completion it would ask the question "Would you like to repeat" and if answer is Y it would run the Main again and it is N it would terminate then and so on. I tried with do...while and no luck any other suggestions?
我确信它应该看起来像这样:
I am sure it should look something like this:
Console.WriteLine("Would you like to repeat? Y/N");
input = Console.ReadKey().KeyChar;
if (input == 'Y') {...}
代码:
class Switch
{
static void Main()
{
Console.Write("Enter your selection (1, 2, or 3): ");
string s = Console.ReadLine();
int n = Int32.Parse(s);
switch (n)
{
case 1:
Console.WriteLine("Current value is {0}", 1);
break;
case 2:
Console.WriteLine("Current value is {0}", 2);
break;
case 3:
Console.WriteLine("Current value is {0}", 3);
break;
default:
Console.WriteLine("Sorry, invalid selection.");
break;
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
.
推荐答案
让我们简化问题:提取方法:
private static void MyRoutine() {
Console.Write("Enter your selection (1, 2, or 3): ");
String input = Console.ReadLine();
int n = 0;
// User Input validation: we want integer value (int.TryParse) in the desired rang
if (!int.TryParse(input, out n)) {
Console.WriteLine("Sorry, invalid selection. Integer value expected");
return;
}
else if (n < 1 || n > 3) {
Console.WriteLine("Sorry, invalid selection. Range of 1..3 expected.");
return;
}
// n is valid
switch (n) {
case 1:
Console.WriteLine("Current value is {0}", 1);
break;
case 2:
Console.WriteLine("Current value is {0}", 2);
break;
case 3:
Console.WriteLine("Current value is {0}", 3);
break;
}
}
现在我们准备继续运行例程( repeat 通常是一个 loop ;这里我们有 do..while
):
Now we are ready to keep on running the routine (repeat is usually a loop; here we have do..while
):
static void Main() {
do {
MyRoutine();
Console.WriteLine("Would you like to repeat? Y/N");
}
while (char.ToUpper(Console.ReadKey().KeyChar) == 'y');
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
这篇关于在C#上再次运行该函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!