首页 > 解决方案 > 如何在 Array[10] 中存储 4 位 PIN 然后提取它们

问题描述

选项 1 添加 PINS ,选项 4 显示它们(2 和 3 未完成),如何在 GetValidInt 方法中修改此代码以将 myInt 存储为字符串?

static void PopulateArray(int[] theArray)
{
    for (int i = 0; i < theArray.Length; i++)
    {
        theArray[i] = GetValidInt($"Please enter 4-Digit PIN or q to exit #{i + 1}: ", 0, 9999);
    }
}

static int GetValidInt(string prompt, int min, int max)
{
    bool valid = false;
    int myInt = -1;
    //string myInt; //trying to convert a int to string
    do
    {
        Console.Write(prompt);
        try
        {
            //myInt = Console.ReadLine();
            myInt = int.Parse(Console.ReadLine());
            if (myInt < min || myInt > max)
            {
                throw new Exception("Provided integer was outside of the bounds specified.");
            }
            valid = true;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Parse failed: {ex.Message}");
        }
    } while (!valid);
    //enter code here
    return myInt;
}

我想首先检查用户是否输入了一个介于 0 和 9999 之间的数字,并且数据可以有前导“0”,因为这些是 PIN 码(例如:“0001”或“0123”)。然后我将它们存储在 [10] 的数组中,稍后根据用户请求检索它们。这就是为什么我首先使用 int 格式来检查 MIN 和 MAX,然后我需要将其转换为字符串进行存储,这样我就不会丢失“零”。我可以将我的范围从 999 限制到 10000,但是我将无法存储像“0001”或“0123”这样的引脚,因为它会将其存储为 1 和 123。

标签: c#arraysstring

解决方案


主要问题是您的代码不遵循操作的自然过程。这是我的建议(利用System.Text.RegularExpressions命名空间):

static Regex PinRegex = new Regex(@"\d{4}");

static bool isPin(string s) => PinRegex.IsMatch(s);

static bool isExit(string s) => s == "q";

static void PopulateArray(string[] theArray)
{
    for (int i = 0; i < theArray.Length; i++)
    {
        Console.Write($"Please enter 4-Digit PIN or q to exit #{i + 1}: ");
        string userAnswer = Console.ReadLine();
        if (isExit(userAnswer))
            exit();  // To be implemented
        else if (isPin(userAnswer))
            theArray[i] = userAnswer;
        else
            unrecognizedAnswer(); // To be implemented
    }
}

推荐阅读