在 C# 中验证 readline 输入的最佳方法?

发布于 2024-07-13 00:03:21 字数 1400 浏览 9 评论 0 原文

哦,有两件事: 1)它是一个控制台应用程序。 2)我知道它是丹麦语的,但这并不重要,它只是一个请求一些输入的例子。 文本和变量并不重要。

好吧,考虑这个简单的输入: 它实际上可以是任何类型的输入问题。

Console.WriteLine("Hvad er dit kundenummer: (Kun hele tal tilladt)");
string inputKnr = Console.ReadLine();
kundenummer = Convert.ToInt16(inputKnr);

现在,如果客户输入错误怎么办? 比如一封信。 尝试& catch 将确保应用程序不会中断,但这不是我想要的解决方案。 我想让它说你做错了,再试一次。 很经典吧?

但解决这个问题的最佳方法是什么? 我已经想到了这一点:

bool fangetKundenummer = true;
while (fangetKundenummer)
{
Console.WriteLine("Hvad er dit kundenummer: (Kun hele tal tilladt)");
string inputKnr = Console.ReadLine();
try
{
    kundenummer = Convert.ToInt16(inputKnr);
    fangetKundenummer = false;
}
catch
{
    Console.WriteLine("Fejl. Prøv igen");
}
}

但这似乎不是正确的方法。

另外,顺便提一下,我正在使用的这个小应用程序有连续 4 个输入问题。 这意味着 4 次这个令人讨厌的 while() 循环。

您还可以编写一个函数。 像这样的东西(没有理由以正确的方式做,它只是为了说明一个概念):

static void verifyInput()
{
    try
    {
        Console.WriteLine("question");
        input = Console.ReadLine();
        kundenummer = Convert.ToInt16(input)
    }
    catch
    {
        Console.WriteLine("Wrong. Do it over");
        verifyInput(); //start the function all over
    }
}

但是你必须为每个输入问题编写一个函数,即使他们可能要求完全相同! (意味着也许所有人都要求一个整数;但有不同的问题和变量)。

这看起来并不比 while() 解决方案好多少。

有人有聪明的主意吗?

Oh, 2 things:
1) It is a console application.
2 ) I know it is in danish, but it doesn't really matter, its just an example of asking for some input. The text and variables does not matter.

Alright, consider this simple input:
It could be any sort of input question really.

Console.WriteLine("Hvad er dit kundenummer: (Kun hele tal tilladt)");
string inputKnr = Console.ReadLine();
kundenummer = Convert.ToInt16(inputKnr);

Now, what if the customer types something wrong? Such as a letter.
A try & catch would make sure the application does not break, but that is not the solution I want.
I want it to say that you did it wrong, try again.
Pretty classic right?

But what is the best way to solve this solution? I have thought of this:

bool fangetKundenummer = true;
while (fangetKundenummer)
{
Console.WriteLine("Hvad er dit kundenummer: (Kun hele tal tilladt)");
string inputKnr = Console.ReadLine();
try
{
    kundenummer = Convert.ToInt16(inputKnr);
    fangetKundenummer = false;
}
catch
{
    Console.WriteLine("Fejl. Prøv igen");
}
}

But it just doesn't seem like the right way to do it.

Also, just to mention it, this little application I am playing with has 4 input questions in a row. This would mean 4 times this nasty while() loop.

You could also write a function. Something like this (no reason to do it the right way, its just to illustrate a concept):

static void verifyInput()
{
    try
    {
        Console.WriteLine("question");
        input = Console.ReadLine();
        kundenummer = Convert.ToInt16(input)
    }
    catch
    {
        Console.WriteLine("Wrong. Do it over");
        verifyInput(); //start the function all over
    }
}

But you'd have to write a function for each and every input question, even though they might ask exactly for the same! (meaning perhaps all asking for an integer; but with a different question and variable).

This doesn't seem much better than the while() solution.

Does anyone have a clever idea?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

古镇旧梦 2024-07-20 00:03:21

使用 Int16.TryParse 以及其他数字的等效项类型。 所有这些都返回一个布尔结果来指示解析成功或失败,并采用一个 out 参数,该参数设置为解析结果(如果失败则为 0)。 在您的情况下,您可能希望将调用包装在一个方法中以不断提示:

static Int16 PromptForInt16(string prompt)
{
    while (true)
    {
        Console.Write(prompt);
        Int16 result;
        if (Int16.TryParse(Console.ReadLine(), out result))
        {
            return result;
        }
        Console.WriteLine("Sorry, invalid number entered. Try again.");
    }
}

Use Int16.TryParse and the equivalents for other numeric types. All of these return a Boolean result to indicate success or failure for parsing, and take an out parameter which is set to the result of the parsing (or 0 in case of failure). In your case you may want to wrap the call in a method to keep prompting:

static Int16 PromptForInt16(string prompt)
{
    while (true)
    {
        Console.Write(prompt);
        Int16 result;
        if (Int16.TryParse(Console.ReadLine(), out result))
        {
            return result;
        }
        Console.WriteLine("Sorry, invalid number entered. Try again.");
    }
}
他不在意 2024-07-20 00:03:21

您可以使用 TryParse 模式:

string s; // for "is not valid" message
short val; // final value
while(!short.TryParse(s=Console.ReadLine(), out val)) {
    Console.WriteLine(s + " is not valid...");
}

You can use the TryParse pattern:

string s; // for "is not valid" message
short val; // final value
while(!short.TryParse(s=Console.ReadLine(), out val)) {
    Console.WriteLine(s + " is not valid...");
}
早茶月光 2024-07-20 00:03:21

只是为了一些变化,测试字符串本身怎么样,而不是 TryParse,这需要额外的存储空间,并且可能需要不需要的强制转换?

static void Main(string[] args)
{
    var isFalse = "t".IsInt();
    var isTrue = "123".IsInt();
    var isAlsoFalse = "123.1".IsInt();

}

static bool IsInt(this IEnumerable<char> s)
{
    return s.All(x => char.IsNumber(x));
}

Just for some variety, how about testing the string itself, instead of TryParse, which would require extra storage, and potentially an unneeded cast?

static void Main(string[] args)
{
    var isFalse = "t".IsInt();
    var isTrue = "123".IsInt();
    var isAlsoFalse = "123.1".IsInt();

}

static bool IsInt(this IEnumerable<char> s)
{
    return s.All(x => char.IsNumber(x));
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文