C# recursive statement in calculator error

725 views c#
2

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.

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()? Or should I call the function conditionally within Main()? Anything else? Thanks in advance!!

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

answered question

1 Answer

9

Add a return before your recursive GetNumber. This will return the recursed value back up the chain before ultimately returning back to your Main method.

You can remove the second if statement entirly, since you'll only be there if res is 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();        
}

posted this

Have an answer?

JD

Please login first before posting an answer.