简体   繁体   中英

Execute a loop until user presses a specific button

I am trying to create a multi functional program. For one part, an array is filled with random numbers. The user then enters in a number and the program returns which positions the number appears in the array. It also returns the number of times the number appears in the array.

However it only does this once and after that it ends the program. I want it to prompt the user to enter in a number to search until the user presses a button, let's say 'P' for example. Once the user presses 'P' after the results are shown, the program should close. Any tips into what methods or functionality I should be using?

Here is a broken down version of my code.

Console.Write("Now enter a number to compare: ");
int c = Convert.ToInt32(Console.ReadLine());

for (int j = 0; j < arr.Length; j++)
{
    if (arr[j] == c)
    {
        pos.Add(j);
    }
}          

if (pos.Count == 0)
{
    Console.WriteLine("Sorry this number does not match");
}
else
{
   Console.WriteLine("The number {0} appears {1} time(s)",c,pos.Count);
}

Console.ReadLine();

this should give you a little head start

you have to use a loop around your code and check for a keyword to exit

class Program
{
    static void Main(string[] args)
    {
        var arr = new int[50];
        var pos = new List<int>();
        string result;
        do
        {
            Console.Write("Now enter a number to compare: ");
            result = Console.ReadLine();

            int c;

            if (int.TryParse(result, out c))
            {
                for (int j = 0; j < arr.Length; j++)
                {
                    if (arr[j] == c)
                    {
                        pos.Add(j);
                    }
                }

                if (pos.Count == 0)
                {
                    Console.WriteLine("Sorry this number does not match");
                }
                else
                {
                    Console.WriteLine("The number {0} appears {1} time(s)", c, pos.Count);
                }
            }


        } while (result != "exit");
    }
}

I am going to provide another approach, didn't test the code below though.

class Program
{

    //declare your class variables here
    //so that you can access them from the methods and do your operations
    bool Up=true;

    static void Main(string[] args)
    {
        Console.WriteLine("Program started.");

        ThreadPool.QueueUserWorkItem(ConsoleCommands);
        while (Up)
        {
            Thread.Sleep(2000);
        }
        Console.WriteLine("Program ended.");
    }

    private static void ConsoleCommands(object dummy)
    {
        while (Up)
        {
            string cmd = ConsoleReceiver().ToLower();
            switch (cmd)
            {
                case "exit":
                    Up=false;
                    break;
                //implement more cases here and fill the rest of your business
                //example:
                case "1":
                    if (pos.Count == Int32.Parse(cmd))//just a dummy business
                    {
                        Console.WriteLine("Sorry this number does not match");
                    }
                    else//another dummy business
                    {
                        Console.WriteLine("Sth...");
                    }
                    break;
                default:
                    Console.WriteLine("Unrecognized command");
                    break;
            }//or forget about switch and use if-else stements instead.
        }
    }

    private static string ConsoleReceiver()
    {
        Console.WriteLine("#cmd:");
        return Console.ReadLine();
    }
}

If you want to explicitly read single keys strokes...

ConsoleKeyInfo keyInfo;
do {
    Console.Write("Enter a number to compare; press the 'p' key to quit: ");
    keyInfo = Console.ReadKey(false);

    int c;
    if (Int32.TryParse(keyInfo.KeyChar.ToString(), out c))
    {    
        for (int j = 0; j < arr.Length; j++)
        {
            if (arr[j] == c)
            {
                pos.Add(j);
            }
        }          

        if (pos.Count == 0)
        {
            Console.WriteLine("Sorry this number does not match");
        }
        else
        {
           Console.WriteLine("The number {0} appears {1} time(s)",c,pos.Count);
        }
} while (keyInfo.Key != ConsoleKey.P)

Otherwise you can get creative with combinations of what @Fredou and I have posted.

Try this :)

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            start:
            string tryagain;


           //All of your Code Goes here


            tryagain = Console.ReadLine();
            if (tryagain != "p")
            {
            goto start;    
            }

            else
            {
                Environment.Exit(0);
            }


        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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