简体   繁体   English

计算器错误中的C#递归语句

[英]C# recursive statement in calculator error

I've created a simple calculator previously, and now I'm trying to improve it with a bit more error handling built in. I'm trying to call a function to read an int, tryparsing, and if it fails to re-call the function until TryParse() is successful. 之前,我已经创建了一个简单的计算器,现在我试图通过内置更多错误处理功能对其进行改进。该函数,直到TryParse()成功。

My issue is that the false path does not return a value so it will not compile. 我的问题是错误的路径不会返回值,因此不会进行编译。 I'm sure there is a simple step I am missing, can anyone help me with some advice? 我确定我缺少一个简单的步骤,有人可以帮助我一些建议吗? Can this problem be fixed within GetNumber() ? 可以在GetNumber()解决此问题吗? Or should I call the function conditionally within Main() ? 还是应该在Main()有条件地调用该函数? Anything else? 还要别的吗?

using System;

class Program
{
    static int GetNumber()
    {
        Console.WriteLine("Enter a number");
        string entry = Console.ReadLine();

        int num;

        bool res = int.TryParse(entry, out num);

        if (res == true)
        {
            return num;
        }

        if (res == false)
        {
            Console.WriteLine("You did not enter a proper number");
            GetNumber();
        }
    }

    static void Main()
    {
        int x = GetNumber();
    }
}

Add a return before your recursive GetNumber . 在递归GetNumber之前添加一个返回值。 This will return the recursed value back up the chain before ultimately returning back to your Main method. 这将把递归的值返回到链中,最后返回到Main方法。

You can remove the second if statement entirly, since you'll only be there if res is false. 您可以完整地删除第二个if语句,因为只有在res为false时您才能在那里。 This doesn't impact the functionality, just makes it a little easier to read. 这不会影响功能,只会使其更易于阅读。

static int GetNumber(){
    Console.WriteLine("Enter a number");
    string entry = Console.ReadLine();
    int num;
    bool res = int.TryParse(entry, out num);
    if (res == true){
        return num;
    }

    Console.WriteLine("You did not enter a proper number");
    return GetNumber();        
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM