vendredi 22 octobre 2021

C#: while versus if

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?

Aucun commentaire:

Enregistrer un commentaire