如何在Main()中初始化状态数组

时间:2019-06-11 18:39:18

标签: c# arrays loops validation main

问题是我不确定如何正确设置代码格式,以便当用户输入状态缩写时,main方法在GetValidState方法中查找它,以使用户知道他们输入的内容是否有效。关键之一是缩写必须长2个字母。

static void Main(string[] args)
{
    string stateAbbreviation;
    bool fieldValidationSuccess = false;

    promt = GetValidState("State (2 letters):\t");
    stateAbbreviation = ReadLine();
}

public static string GetValidState(string prompt, string[] sortedStateArray)
{
    string[] states = new string[] { "AK", "WA", "OR", "CA", "AZ", "NM", "CO", "UT" };

    fieldValidationSuccess = false;

    while (!fieldValidationSuccess)
    {
        int sub = 0;
        while (sub < states.Length && !fieldValidationSuccess)
        {
            if (states[sub].ToUpper() == stateAbbreviation.ToUpper())
            {
                fieldValidationSuccess = true;
            }
            else
            {
                sub++;
            }
        }

        if (!fieldValidationSuccess)
        {
            WriteLine("\n***ERROR.  We do not ship to {0}.", stateAbbreviation);
        }
    }
}
  • 在Main()中初始化状态数组。

•建立一个验证循环,以确保用户输入有效的状态缩写。

•使用循环在数组中搜索有效状态。不要使用Array.BinarySearch

•调用GetValidString从用户获取字符串。最小和最大参数都使用2。

1 个答案:

答案 0 :(得分:0)

我不确定这是否是您想要的。您想要一个代码来检查STATE是否在您的数组中?

        public static void GetValidState(string prompt, string state)
        {
            string[] states = new string[] { "AK", "WA", "OR", "CA", "AZ", "NM", "CO", "UT" };

            if (!states.Contains(state))
                WriteLine("\n***ERROR.  We do not ship to {0}.", state);

        }