c# - 将while循环放入方法中
问题描述
有没有办法将方法内部的 while 循环AddToStock
放入单独的ValidateInput
方法中?我也附上了ReadInteger
代码。(类似于 ReadDecimal/ReadString/ReadDate)
AddToStock 代码:
private static void AddToStock()
{
//Get item id
int itemid = ReadInteger("\nItem ID:");
//Confirm item id is greater than 0
while (itemid <= 0)
{
Console.WriteLine("Item ID Cannot Be Less Than 1, Please Try Again");
//Get item id
itemid = ReadInteger("Item ID:");
}
//Get item name
string itemname = ReadString("Item Name:");
//While item name input empty
while (string.IsNullOrWhiteSpace(itemname))
{
Console.WriteLine("You Didn't Enter An Item Name, Please Try Again");
itemname = ReadString("Item Name:");
}
//Get item quantity
int itemquantity = ReadInteger("Quantity:");
//Confirm item quantity is greater than 0
while (itemquantity <= 0)
{
Console.WriteLine("Quantity Cannot Be Less Than 1, Please Try Again");
//Get item quantity
itemquantity = ReadInteger("Quantity:");
}
//Get item price
decimal itemprice = ReadDecimal("Price Paid:");
//Confirm item price is greater than 0
while (itemprice <= 0)
{
Console.WriteLine("Item Price Cannot Be Less Than Or Equal To £0.00, Please Try Again");
//Get item price
itemprice = ReadDecimal("Item Price:");
}
//Get item date added
DateTime itemdate = ReadDate("Date Added:");
//Add item to stock
Employee_UI.AddToStock(itemid, itemname, itemprice, itemquantity, itemdate);
Console.WriteLine("\nItem Added To Stock!");
}
读取整数代码:
private static int ReadInteger(string prompt)
{
while (true)
{
Console.WriteLine(prompt);
try
{
Console.Write("> ");
return Convert.ToInt32(Console.ReadLine());
}
//If input not integer
catch (Exception)
{
Console.WriteLine("Couldn't Understand That As A Number, Please Try Again");
}
}
}
任何帮助深表感谢!对这一切还是陌生的:)
解决方案
无需创建其他方法。您可以简单地修改您的ReadInteger
方法来检查输入整数是否在范围内。
注意:与其使用Convert.ToInt32()
和捕获异常,不如遵循标准的方式,即使用int.TryParse()
方法。
尝试这样的事情:
private static int ReadInteger(string prompt, int minimum = int.MinValue)
{
while (true)
{
Console.WriteLine(prompt);
Console.Write("> ");
int value;
if (!int.TryParse(Console.ReadLine(), out value))
{
Console.WriteLine("Couldn't Understand That As A Number, Please Try Again");
}
else if (value < minimum)
{
Console.WriteLine($"The number Cannot Be Less Than {minimum}. Please Try Again");
}
else
{
return value;
}
}
}
用法:
int itemid = ReadInteger("\nItem ID:", minimum: 1);
ReadXXXX
然后,您可以对其他方法遵循相同的逻辑。
推荐阅读
- git - 无法推送到 Git 服务器
- angular - 如何从 2 个数组中检索值并以特定格式显示
- r - 修正后增强回归树中残差的空间自相关
- c# - 在 LockState 中通过 PhoneScreen 显示 Toast
- ios - 单视图应用程序具有无法更改的黑色背景
- lldb - 如何访问结构中的字段
- javascript - Google Map API (JS) - 在 Google 地图中显示多个位置,但一个接一个
- php - 如何在 Symfony 4 中找到通往 GET/users 的路线
- angular - 如何使用专辑 ID 显示每个专辑的图像?
- uwp - GetProductInfo() 在 UWP 应用程序中给出异常