【问题标题】:How to implement Method that calls itself?如何实现调用自身的方法?
【发布时间】:2012-07-10 06:00:33
【问题描述】:

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

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

我写的代码是这样的。

 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;
        }
  }

【问题讨论】:

  • 我假设他们期待一个显式循环?
  • 您在寻找循环吗?参见例如while 关键字。
  • 这段代码的一个更糟糕的风格问题是使用了全局变量。
  • @BenVoigt - 他们很可能从私有方法访问类成员。我看不出这有什么问题。理想情况下,虽然我尽量保持我的功能尽可能纯,但你不能总是这样做。
  • @ChaosPandion:num 没有充分的理由成为班级成员,并且有几个理由让它成为本地成员。这是一种糟糕的风格。

标签: c# recursion loops


【解决方案1】:

我个人有点喜欢这种风格,但它效率低下(如果用户多次输入无效输入,可能会导致堆栈溢出)。您的讲师可能希望您使用 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.
}

【讨论】:

  • 在 C 中,您可能会遇到显式相等检查和“布尔值”(比如 TRUE == SomeMethod() 和 SomeMethod 返回 -1 而不是 !0)的不幸问题。布尔值根本不应该针对“假”或“真”进行显式测试。
  • @sixlettervariables:在 C 中,1 == !0。也许你的意思是-1,或者~0
  • @sixlettervariables:你是对的;我把两个问题混为一谈。我改写了评论,以免误导性地挑出 C 语言。
  • 哈哈,好吧,我已经切换到 while (!int.TryParse(Console.ReadLine(), out num)) 只是为了减少眉毛! ;)
【解决方案2】:

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

int num;
while (!int.TryParse(Console.ReadLine(), out num))
{
    Console.WriteLine("Your input is not valid, please try again.\n");
}

【讨论】:

  • 感谢大家的帮助! num 是一个 gonner ;) 我移动它以获得更好的风格 :) 我之前尝试过同时进行 while 和 switch/case 工作,但我现在不能让你有一个 while 循环运行和工作。我要学习编码的东西太多了,而且我学得越多似乎就越多。
  • @user1501127 - 抬起头来,记住我们都必须从零开始。
【解决方案3】:

使用 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循环比较好。

【讨论】:

  • @sixlettervariables OP 声明“我喜欢编码,所以我只需要以正确的方式轻推!:)”我轻推的意思是“你应该看看一个循环”。您应该学习如何回答实际问题,而不是吹毛求疵。
  • 我认为这个变量只会增加太多的语法噪音。
  • @ChaosPandion 是的,写得很快。本来想用do循环的,后来发现“请给...”的文字必须再打印一次,所以我改写了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-22
  • 2016-01-30
  • 2012-09-14
  • 1970-01-01
  • 2015-02-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多