[英]More efficient way of input checking?
New programmer here! 新程序员在这里! I'm just wondering if there is a more efficient way of checking the input in the code below? 我只是想知道在下面的代码中是否有更有效的方法来检查输入?
I use a while loop in combination with TryParse to see if the input is valid. 我使用while循环与TryParse结合来查看输入是否有效。 As you can see, I'm reusing the code. 如您所见,我正在重用代码。 I would like to do something similar with the first user input as well. 我想用第一个用户输入做类似的事情。 Basically it's a piece of code that I will be able to re-use many times in a program. 基本上它是一段代码,我将能够在程序中多次重复使用。
Is there any way to make this more efficient without re-writing the code all the time? 有没有办法在不重写代码的情况下提高效率? Could this be implemented in a function of sorts? 这可以在各种功能中实现吗?
namespace Calculator2
{
class GetUserInput
{
public char MethodChoice;
private string _numberOne;
private string _numberTwo;
public int NumberOne;
public int NumberTwo;
public void GetCalculationMethod()
{
Console.WriteLine("Welcome to calculator v.2!");
Console.WriteLine("Please choose a method of calculation!");
Console.WriteLine("1: Addition");
Console.WriteLine("2: Subtraction");
Console.Write("Your choice: ");
MethodChoice = Console.ReadKey().KeyChar;
}
public void GetCalculationNumbers()
{
Console.Clear();
Console.WriteLine("Please enter two numbers...");
while (!int.TryParse(_numberOne, out NumberOne))
{
_numberOne = Console.ReadLine();
if (!int.TryParse(_numberOne, out NumberTwo))
{
Console.WriteLine("Invalid input, try again!");
}
}
Console.WriteLine("Number two: ");
while (!int.TryParse(_numberTwo, out NumberTwo))
{
_numberTwo = Console.ReadLine();
if (!int.TryParse(_numberTwo, out NumberTwo))
{
Console.WriteLine("Invalid input, try again!");
}
}
}
}
}
Your code doesn't seem quite right. 你的代码看起来不太对劲。 It never reads the user's input until after TryParse()
fails. 在TryParse()
失败之前,它永远不会读取用户的输入。 Also, it's a red flag to call TryParse()
twice for the same input. 此外,对于相同的输入,两次调用TryParse()
是一个红色标志。
At any rate, the most obvious way to eliminate repeated code is to move the repeated code into a separate method, and then just call that method. 无论如何,消除重复代码的最明显方法是将重复的代码移动到单独的方法中,然后调用该方法。
For example: 例如:
int GetInteger(string prompt)
{
Console.WriteLine(prompt);
while (true)
{
string s = Console.ReadLine();
int value;
if (int.TryParse(s, out value))
return value;
Console.WriteLine("Invalid input, try again!");
}
}
And then use it like this: 然后像这样使用它:
public void GetCalculationNumbers()
{
Console.Clear();
NumberOne = GetInteger("Please enter two numbers...");
NumberTwo = GetInteger("Number two: ");
}
Note that you should add a way for the user to cancel, in case they don't want to complete the input. 请注意,如果用户不想完成输入,则应为用户添加取消方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.