dimanche 27 août 2017

In C#, what would be a nicer way to show this while loop?

namespace StringProgramFruits
{
public class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("What is your favourite fruit?, (Apples), (Bananas), (Kiwi) or (Peaches)?");
        string fruit = Console.ReadLine();
        if (fruit == "Apple")
        {
            Console.WriteLine("Apples!");
        }
        if (fruit == "Kiwi")
        {
            Console.WriteLine("Kiwi!");
        }
        if (fruit == "Bananas")
        {
            Console.WriteLine("Bananas!");
        }
        while (fruit != "Apple") while (fruit != "Bananas") while (fruit != "Kiwi")
                {
                    Console.WriteLine("Try Again!");
                    fruit = Console.ReadLine();
                    if (fruit == "Apple")
                    {
                        Console.WriteLine("Apples!");
                    }
                    if (fruit == "Kiwi")
                    {
                        Console.WriteLine("Kiwi!");
                    }
                    if (fruit == "Bananas")
                    {
                        Console.WriteLine("Bananas!");
                    }
                    return;

                }
    }
}

If you look at the while loop there, I just added 3 while functions in a single line to add more conditions. This doesn't look very nice in the code base, so I was wondering if there was a different or easier way to add multiple conditions to while loops. I have tried using

while (fruit != "Apple") || (fruit != "Bananas") || (fruit != "Kiwi")

but the above code just showed up as an invalid expression :/

It's probably quite apparent that I am very new to C-sharp, and while this is a very trivial question, I would still like to know if there is any other way nonetheless.

Aucun commentaire:

Enregistrer un commentaire