user7176008 user7176008 - 10 days ago 4
C# Question

Nested While Loop where "Not all code paths return a value"

For the program that I am trying to write I need to use both a Switch case and a While loop. I have no problem with the Switch example, however I'm not sure how to get a similar solution with a While loop.

I am trying to evaluate a user entered value with a nested while loop.
In it I want to allow the user to "select" any number between and including 3 through 10. (Assume that using System etc is all correct)

static void Main()
{
int userInput; //user enters int with ReadLine
int defaultInt = 3; //user keys anything other than 3 through 10

Console.WriteLine("Enter an Integer");
userInput = int.Parse(Console.ReadLine());
InputCheck();
Console.WriteLine("The number you have chosen is {0}", userInput

}

public int InputCheck()
{
while (userInput >= 3)
{
while (userInput <= 10)
{
return userInput;
}
while (userInput > 10)
{
return defaulInt = userInput;
}
while (userInput < 3)
{
return defaultInt = userInput;
}
}


Is something like this even possible to do with a while loop?
I know it would be easier to do this as a Switch but I have already done that in this program and need to implement a While loop.

Answer

if statement is actually what you are looking for, not while.
Talking about if usage, code convenience and readability, I would also rearrange it this way:

public int InputCheck()
{
    if (userInput > 10) 
        return defaultInt = userInput;

    if (userInput >= 3)
        return userInput;

    return defaultInt = userInput;
}

Look, it now looks better, but does the same thing.
Two of your if conditions were actually redundant since they are guaranteed to be true according to previous conditions.

However, your code is still non-working...

  1. What is that: defaultInt = userInput? Do you really want to override the value of defaultInt. Name default suggests that it shouldn't be.
  2. Also, you try to access local variables in another method, which is impossible.
  3. You are missing a couple parentheses and curly braces.

Please, be sure to fully read and understand this material before asking next questions:

Comments