0

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

    }
  }
}
6
  • 1
    try foreach (.. with that string Commented Oct 31, 2012 at 2:13
  • 2
    What would be the exit condition ... If you no longer wish to select more fruits? Commented Oct 31, 2012 at 2:15
  • have you tied typing for then pressing tab? It should give you the skeleton of the proper syntax. Commented Oct 31, 2012 at 2:15
  • 2
    I don't understand what are you trying to achieve. Could you explain what the user would expect of this program? Commented Oct 31, 2012 at 2:16
  • @Brad thanks for the heads up on the syntax skeleton. Never knew about that function! Commented Oct 31, 2012 at 4:34

4 Answers 4

2

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);
Sign up to request clarification or add additional context in comments.

4 Comments

it's better create condition in while statement until user finish to select optional fruit
I think so but the condition for he to decide :)
Works well and does the job. Need to find a way to exit though, maybe Enviornment.Exit() ?
I just add a way to exit. This way is if u add a input outside the case above it will break out the loop and program close.
1

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

Comments

1

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.