Why does my loop work with & ldquo; & amp; & amp; & rdquo; operator but not & ldquo; || & rdquo; or & ldquo; ^ & rdquo;?

advertisements

The code asks the user whether he/she has eaten something or not. Then it loops the question until a valid input (such as "nothing" or "something") is entered. My problem is that when I use the "||" operator, the loop continues no matter what is inputted. To my understanding, the loop should end when the user inputted string is equal to "nothing", "something", or both based on the operator I'm using. But this result only occurs when I use the "&&" operator, which confuses me as that would mean that the user would have to input a string value equal to "nothing" AND "something". So my question is why does my loop work with the "&&" operator but not "||" or "^" operator ? Thanks in advance.

struct multivar
{
    public int userInt;
    public string userText;
}
class Program
{
    static void Main(string[] args)
    {
        multivar structHolder;
        string shrinkRay = "";
        while ((shrinkRay != "nothing") || (shrinkRay != "something"))
        {
            Console.WriteLine("What did you eat today?\n1)Nothing?\n2)Something?");
            structHolder.userText = Console.ReadLine();
            shrinkRay = structHolder.userText.ToLower();
            if ((shrinkRay != "nothing") || (shrinkRay != "something"))
            {
                Console.WriteLine("Please input a valid response such as \"Nothing\" or \"Something\".");
            }
        }


your logic:

str != 1 || str != 2

can be rewritten as

!(str == 1 && str == 2)

its obvious one of the inner statements must be false, so the whole inner statement will be false. The negation will make the statement true, always. You need to alter your logic as others have said.