简体   繁体   中英

C# Looping a block of code (containing an array)

Just a bit lost here. My issue is that I have written a simple block of code which allows a user to select a fruit. The code does what I want it to do bar one issue, I need it to loop back to the start of the code in order for the user to re-select one of the optional fruit.

However, I can't seem to get it working but I suspect the problem is my understanding of loops which will require more attention. I understand I would need an initializer and a condition of some kind for the loop to execute. I have tried many (crazy) things including trying to execute the loop like this : for (string[ ] fruitArray = {"Banana", "Apple", "Orange", "Pineapple"}); but the compiler is having none of it and I imagine the Stack overflow community wouldn't accept that either. Any help and advice is appreciated.

{

            Console.WriteLine("\n", "\n");

            string[] fruitArray = {"Banana", "Apple", "Orange", "Pineapple"};

            Console.WriteLine("Please select your fruit: \n\n{0} \n{1} \n{2} \n{3}" + "\n", fruitArray[0], fruitArray[1], fruitArray[2], fruitArray[3]);
            string selection = Console.ReadLine();


            if (selection == fruitArray[0])
            {
                Console.WriteLine("\nYou have selected {0} ", fruitArray[0]);
            }
            else if (selection == fruitArray[1])
            {
                Console.WriteLine("\nYou have selected {0} ", fruitArray[1]);
            }
            else if (selection == fruitArray[2])
            {
                Console.WriteLine("\nYou have selected {0} ", fruitArray[2]);
            }
            else if (selection == fruitArray[3])
            {
                Console.WriteLine("\nYou have selected {0} ", fruitArray[3]);
            }
            else
            {
                Console.WriteLine("\nSelection not recognised. Please select fruit: ");
            }

         }

        Console.ReadKey();

    }
  }
}

Loop without exit

while (true)
            {
                Console.WriteLine("\n", "\n");

                string[] fruitArray = { "Banana", "Apple", "Orange", "Pineapple" };

                Console.WriteLine("Please select your fruit: \n\n{0} \n{1} \n{2} \n{3}" + "\n", fruitArray[0], fruitArray[1],
                                  fruitArray[2], fruitArray[3]);
                string selection = Console.ReadLine();

                switch (selection)
                {
                    case "Banana":
                        Console.WriteLine("\nYou have selected {0} ", fruitArray[0]);
                        break;

                    case "Apple":
                        Console.WriteLine("\nYou have selected {0} ", fruitArray[1]);
                        break;

                    case "Orange":
                        Console.WriteLine("\nYou have selected {0} ", fruitArray[2]);
                        break;

                    case "Pineapple":
                        Console.WriteLine("\nYou have selected {0} ", fruitArray[3]);
                        break;                    
                } 
            }          

Loop with exit condition

            var isLoop = true;

            do
            {
                Console.WriteLine("\n", "\n");

                string[] fruitArray = {"Banana", "Apple", "Orange", "Pineapple"};

                Console.WriteLine("Please select your fruit: \n\n{0} \n{1} \n{2} \n{3}"   + "\n", fruitArray[0],
                                  fruitArray[1],
                                  fruitArray[2], fruitArray[3]);
                string selection = Console.ReadLine();


                switch (selection)
                {
                    case "Banana":
                        Console.WriteLine("\nYou have selected {0} ", fruitArray[0]);
                        break;

                    case "Apple":
                        Console.WriteLine("\nYou have selected {0} ", fruitArray[1]);
                        break;

                    case "Orange":
                        Console.WriteLine("\nYou have selected {0} ", fruitArray[2]);
                        break;

                    case "Pineapple":
                        Console.WriteLine("\nYou have selected {0} ", fruitArray[3]);
                        break;
                    default:
                    isLoop = false;
                    break;
                }
            } while (isLoop);

C# For http://msdn.microsoft.com/en-us/library/ch45axte.aspx

C# foreach http://msdn.microsoft.com/en-us/library/ttw7t8t6.aspx

string[] fruitArray = { "Banana", "Apple", "Orange", "Pineapple" };

        Console.WriteLine("Please select your fruit: \n");            
        foreach (string fruit in fruitArray)
        {
            Console.Write("\n{0}", fruit);
        }

        Console.WriteLine();



            string selection = Console.ReadLine();
            for (int index = 0; index < fruitArray.Length; index++)
            {
                if (fruitArray[index].Equals(selection))
                {
                    Console.WriteLine("\nYou have selected {0} ", fruitArray[index]);
                    break;
                }
            }

            foreach (string fruit in new[] {"Banana", "Apple", "Orange", "Pineapple" })
            {
                if (fruit.Equals(selection))
                {
                    Console.WriteLine("\nYou have selected {0} ", fruit);
                    break;
                }
            }

For your example, this should be enough:

string[] fruitArray = { "Banana", "Apple", "Orange", "Pineapple" };

Console.WriteLine("Please select your fruit: \n\n{0} \n{1} \n{2} \n{3}" + "\n", fruitArray[0], fruitArray[1],
                              fruitArray[2], fruitArray[3]);
string selection = Console.ReadLine();

Console.WriteLine("\nYou have selected {0} ", selection);

Probably I'm missing something, I'll be glad to understand what :)

Also, you can just improve the first message by iterating the array:

Console.WriteLine("Please select your fruit: \n");

for(int i=0;i<fruitArray.Length;i++)
{
    Console.WriteLine(fruitArray[i]);
}

Hope it helps.

The following code should do exactly what you want. Not only that, but it simplifies the need to even use block if statements or a switch , a simple Array.FindIndex is enough to determine if the input is valid or not. Also, I added an exit clause which so the user can quit the application when they are finished and to remove any cluttering of the UI I am clearing the console window after each "iteration".

    static void Main(string[] args)
    {
        var selection = "";
        while (selection != "q")
        {
            Console.WriteLine(Environment.NewLine);
            string[] fruitArray = { "Banana", "Apple", "Orange", "Pineapple" };

            Console.WriteLine("Please select your fruit (or Q to quit): \n\n{0} \n{1} \n{2} \n{3}", fruitArray[0], fruitArray[1], fruitArray[2], fruitArray[3]);
            Console.Write(Environment.NewLine + "-> ");
            selection = Console.ReadLine().ToLower();

            // valid option selected
            var index = Array.FindIndex(fruitArray, (fruit) => fruit.ToLower() == selection);
            if (index > -1)
            {
                Console.Write("\nYou have selected {0}.", fruitArray[index]);
                ContinuePrompt();
            }
            else if (selection != "q")
            {
                Console.Write("\nSelection not recognised.");
                ContinuePrompt();
            }
        }
     }

    static void ContinuePrompt()
    {
        Console.Write(" Press any key to continue...");
        Console.ReadKey();
        Console.Clear();
    }

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