c# - 如何在 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。
解决方案
主要问题是您的代码不遵循操作的自然过程。这是我的建议(利用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
}
}
推荐阅读
- ruby-on-rails - 当我删除助手时,Rails 5 Action Controller Routing 错误
- ios - webview加载时加载动画卡住/冻结
- android - 我想在实时 FIrebase 中存储纬度和经度......并且有以下代码
- hadoop - distcp 没有执行
- angular - 如何在嵌套的 Observables 中返回 Observable?
- symfony - Symfony 4 服务在资源文件中声明时被忽略
- angular - 没有 HTTPS 的 IdentityServer4 不起作用
- php - 数组中的 if 语句
- postgresql - 从 PostgreSQL 中的 JSON 数组索引和查询 int 值
- java - PostgreSQL 驱动程序问题