问题描述
无法在网站上找到任何其他涵盖此内容的答案.如果运行else并显示错误信息,是否可以通过循环回到开始而不是重新启动控制台来重新启动程序?
Couldn't find any other answer on the site that covers this. If else is run and an error message is displayed, is it possible to restart the program by looping back to the start instead of restarting the console?
class Program
{
static void Main(string[] args)
{
int User;
int Array;
StreamWriter outfile = new StreamWriter("C://log.txt");
Console.WriteLine("Input an number between 1 and 100");
User = Convert.ToInt32(Console.ReadLine());
if (User < 101 && User > 0)
{
for (Array = 1; Array <= User; Array++)
{
Console.WriteLine(Array + ", " + Array * 10 * Array);
outfile.WriteLine(Array + ", " + Array * 10 * Array);
}
{
Console.WriteLine("Press Enter To Exit The Console");
outfile.Close();
Console.ReadLine();
}
}
else
{
Console.WriteLine("Sorry you input an invalid number. ");
Console.ReadLine();
}
}
}
对不起!为了更清楚,如果用户输入无效数字,我需要重新启动程序
Sorry! To be more clear I need to make the Program start again if the user inputs an invalid number
感谢您的帮助!
推荐答案
一种简单的方法是将代码放入 while 循环中,以便代码不断重复.退出循环的唯一方法是让您刚刚在 if
子句中设置的条件为真.所以类似的东西:
An easy way of doing this is placing your code inside a while loop, so that the code keeps repeating. The only way to exit the loop would be for the condition you just set in the if
clause to be true. So something along the lines of:
class Program
{
static void Main(string[] args)
{
int User;
int Array;
bool isUserWrong = true; //This is a flag that we will use to control the flow of the loop
StreamWriter outfile = new StreamWriter("C://log.txt");
while(isUserWrong)
{
Console.WriteLine("Input an number between 1 and 100");
User = Convert.ToInt32(Console.ReadLine());
if (User < 101 && User > 0)
{
for (Array = 1; Array <= User; Array++)
{
Console.WriteLine(Array + ", " + Array * 10 * Array);
outfile.WriteLine(Array + ", " + Array * 10 * Array);
}
isUserWrong = false; // We signal that we may now leave the loop
}
else
{
Console.WriteLine("Sorry you input an invalid number. ");
Console.ReadLine();
//Note that here we keep the value of the flag 'true' so the loop continues
}
}
Console.WriteLine("Press Enter To Exit The Console");
outfile.Close();
Console.ReadLine();
}
}
这篇关于如果 else 为真,我怎样才能让程序循环回到开头?C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!