1

在涵盖此问题的网站上找不到任何其他答案。如果运行 else 并显示错误消息,是否可以通过循环回到开头而不是重新启动控制台来重新启动程序?

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();
            }
    }
}

对不起!为了更清楚,如果用户输入无效数字,我需要重新启动程序

谢谢您的帮助!

4

2 回答 2

4

你可以这样做

User = Convert.ToInt32(Console.ReadLine());
while (User >= 101 || User <= 0) 
{
    Console.WriteLine("Sorry you input an invalid number. ");
    User = Convert.ToInt32(Console.ReadLine());
}
于 2013-11-04T19:03:59.267 回答
3

一个简单的方法是把你的代码放在一个while循环中,这样代码就会不断重复。退出循环的唯一方法是让您刚刚在if子句中设置的条件为真。所以类似于:

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();
    }
}
于 2013-11-04T19:06:42.147 回答