繁体   English   中英

如果其他情况正确,如何使程序循环回到起点? C#

[英]How can I make a program loop back to the start if else is true? C#

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

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

抱歉! 更清楚地说,如果用户输入的数字无效,我需要使程序重新启动

谢谢您的帮助!

你可以这样做

User = Convert.ToInt32(Console.ReadLine());
while (User >= 101 || User <= 0) 
{
    Console.WriteLine("Sorry you input an invalid number. ");
    User = Convert.ToInt32(Console.ReadLine());
}

一种简单的方法是将代码放入while循环中,以使代码不断重复。 退出循环的唯一方法是将您刚刚在if子句中设置为true的条件。 因此,遵循以下原则:

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

这对于Java中的do-while循环将是一个很好的用法:

class DoWhileDemo {
    public static void main(String[] args){
        int count = 1;
        do {
            System.out.println("Count is: " + count);
            count++;
        } while (count < 11);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM