【问题标题】:How to Initialize state array in Main()如何在 Main() 中初始化状态数组
【发布时间】:2019-10-26 05:48:54
【问题描述】:

问题是我不确定如何正确格式化代码,以便当用户输入状态缩写时,主要方法会在 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 从用户那里获取字符串。对 min 和 max 参数都使用 2。

【问题讨论】:

  • 欢迎来到 Stack Overflow。最后的项目符号列表看起来像家庭作业。是这样的吗?
  • stateAbbreviationMain 方法中本地定义。也许您应该将该行移到您需要的GetValidState 方法中?

标签: c# arrays loops validation main


【解决方案1】:

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

        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);

        }

【讨论】:

    猜你喜欢
    • 2019-01-28
    • 2020-07-01
    • 1970-01-01
    • 2019-05-08
    • 1970-01-01
    • 2012-08-25
    • 2019-01-25
    • 2020-10-18
    • 1970-01-01
    相关资源
    最近更新 更多