4

我的手腕被打了一巴掌,因为在一个作业中,当输入错误发生时,我有一个方法调用本身。我不知道如何或使用什么来代替我编写的代码。我需要帮助才能找到正确的方法。

我喜欢编码,所以我只需要以正确的方式轻推!:)

我写的代码是这样的。

 private void SumTheNumbers()
 {
 Console.Write("Please give the value no "+ index + " :");
        if (false == int.TryParse(Console.ReadLine(), out num))
        { 
            //Errormessage if the user did not input an integer.
            Console.WriteLine("Your input is not valid, please try again.");
            Console.WriteLine();
            sum = 0;
            SumTheNumbers();
        }
        else
        {
            //Calculate the numbers given by user
            sum += num;
        }
  }
4

3 回答 3

8

我个人有点喜欢这种风格,但它效率低下(如果用户多次输入无效输入,可能会导致堆栈溢出)。您的讲师可能希望您使用while循环:

Console.Write("Please give the value no "+ index + " :");
while (false == int.TryParse(Console.ReadLine(), out num))
{ 
    //Errormessage if the user did not input an integer.
    Console.WriteLine("Your input is not valid, please try again.");
    Console.WriteLine();
    sum = 0;
}

//Calculate the numbers given by user
sum += num;

顺便说一句,这false ==一点非常不习惯,并且会引起大多数团队的注意(作为旁注:如果你的教练建议你写这个,他/她可能来自不同的语言背景,这是为了防止意外分配;相信我,在 C# 领域中没有必要或正常)。这看起来更典型:

while (!int.TryParse(Console.ReadLine(), out num))
{
    // etc.
}
于 2012-07-10T17:37:05.057 回答
7

实现这一点的标准方法是使用 while 循环。

int num;
while (!int.TryParse(Console.ReadLine(), out num))
{
    Console.WriteLine("Your input is not valid, please try again.\n");
}
于 2012-07-10T17:36:35.027 回答
1

使用 while 循环。

Console.Write("Please give the value no "+ index + " :");
while(!int.TryParse(Console.ReadLine(), out num))   //I find "!" easier to read then "false == "
{
    Console.WriteLine("Your input is not valid, please try again.");
    Console.WriteLine();
    Console.Write("Please give the value no "+ index + " :");
}

这里不需要递归,所以 do while 循环更好。

于 2012-07-10T17:43:20.907 回答