I am trying to develop a method which will check a users input, and only return the input, if it passes validation.
this is what I want to do:
- User enters input
- Check value of input
- If input satisfies logic, then return that value, else call the function again.
this is really what I want, but the complier states that not all code paths return a value:
public static int UserInput(){
int input = int.Parse(Console.ReadLine());
if (input < 1 || input > 4){
Console.Write("Invalid Selection. Enter a valid Number (1,2,3 or 4): ");
if (input < 1 || input > 4) UserInput();
} else{
return input;
}
}
However, this is the following code that satisfies the complier.
public static int UserInput()
{
int input = int.Parse(Console.ReadLine());
if (input < 1 || input > 4)
{
Console.Write("Invalid Selection. Enter a valid Number (1,2,3 or 4): ");
if (input < 1 || input > 4)
{
UserInput();
return -1; // Never reached, but must be put in to satisfy syntax of C#
}
return input; // Never reached, but must be put in to satisfy syntax of C#
}
else
{
return input;
}
}
This kind of works, but I get strange results. If a user was to enter in an input that is either 1,2,3 or 4 in the first go (i.e if statement evaluates to false), then the returned input is whatever the user entered. However, if the user was to enter a value that was not 1,2,3 or 4 then enter a valid number, then program would do the following:
- return input;
- jump into the child if statement and run UserInput();
- then return -1.
You need to
return UserInput();by the looks of it. It simply looks like a recursive function that will drill down and return at the bottom by continually calling itself until a satisfactory constaint is met.What you are doing is drilling down, letting it return a value, then returning a -1 on top of that.
You are also duplicating yourself by checking input again. It looks like this could be boiled down to the following:
So, what will happen is that if the user enters an invalid number, it will call itself again. If they then enter a valid number. The method will return to the first call, which will take that value and return it back up to the original call.
Here is how a recursive call using this would look like: