Home > Mobile >  C#: while versus if
C#: while versus if

Time:10-23

I want to only accept uppercase two letter abbreviations for state that are: AK, WA, OR, CA, AZ, NM, CO, or UT. If the input is not one of those, request a new input from the user to correct. My code below works to filter results, but when I enter "UT" or "WA" it does not exit the while loop and continues.

Write("State (We only ship to AK, WA, OR, CA, AZ, NM, CO, or UT):\t");
            stateName = Convert.ToString(ReadLine().ToUpper());
            while (!stateName.Contains("AK") || !stateName.Contains("WA") || !stateName.Contains("OR") 
                || !stateName.Contains("CA") || !stateName.Contains("AZ") || !stateName.Contains("NM") 
                || !stateName.Contains("CO") || !stateName.Contains("UT"))
            {
                Write("Error: We do not ship to {0}. We ONLY ship to AK, WA, OR, CA, AZ, NM, CO, or UT\t", stateName);
                stateName = Convert.ToString(ReadLine().ToUpper());
            }

Revising it further, I got it to work with:

Write("State (We only ship to AK, WA, OR, CA, AZ, NM, CO, or UT):\t");
            stateName = Convert.ToString(ReadLine().ToUpper());
            if (stateName != "AK" || stateName != "WA" || stateName != "OR"
                || stateName != "CA" || stateName != "AZ" || stateName != "NM"
                || stateName != "CO" || stateName != "UT")
            {
                Write("Error: We do not ship to {0}. We ONLY ship to AK, WA, OR, CA, AZ, NM, "  
                    "CO, or UT\t", stateName);
                stateName = Convert.ToString(ReadLine().ToUpper());
            }

My question is why didn't the while loop work if the logic was very similar? And is the !variableName different than variableName != value?

CodePudding user response:

The problem is your logic, you should be using And && operator instead of Or ||:

while (
    !stateName.Contains("AK") && !stateName.Contains("WA") && !stateName.Contains("OR")
    && !stateName.Contains("CA") && !stateName.Contains("AZ") && !stateName.Contains("NM")
    && !stateName.Contains("CO") && !stateName.Contains("UT"))

enter image description here

I assume you are learning so I went along with this code. In real world scenarios, you should use array to check for so many conditions like this instead (you will need to know for loop and Array).

  • Related