【发布时间】:2020-08-15 17:32:17
【问题描述】:
选项 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。
【问题讨论】:
-
为什么要将
myInt存储为字符串,作为返回int的方法?