-3

I am trying to write a method that will check to see if a number is positive or not and I keep getting an error that says "not all code paths return a value" and I am unsure what I am doing wrong...

public static double IsValad(double x)
{
    Boolean loopValue = true;
    while (loopValue == true)
    {
        if (x > 0)
        {
            loopValue = false;
            return x;
        }
        else
        {
            Console.WriteLine("Error: Please enter a positive value.");
            x = double.Parse(Console.ReadLine());
           return x;
        }
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
  • Your not returning a variable of type double outside of your while. add a return x; statement outside of the while clause. – Robin Nov 07 '18 at 19:43
  • what is this `while` loop for? – derHugo Nov 07 '18 at 19:44
  • 3
    The compiler doesn't know that the `while` loop will ever execute. Yes, you define `loopValue=true` right before the loop, but it thinks that it is possible to have loop value from the start. If the `while` loop is false at the start, no value is returned. Use a `do...while` loop to fix this – eye_am_groot Nov 07 '18 at 19:44
  • 4
    You are always returning in the first iteration so the while loop is actually pointless. – Selman Genç Nov 07 '18 at 19:46
  • 4
    Possible almost **word for word** duplicate of [c# returning error "not all code paths return a value"](https://stackoverflow.com/questions/21197410/c-sharp-returning-error-not-all-code-paths-return-a-value) – Gabriel Devillers Nov 07 '18 at 19:47

2 Answers2

0

You are not returning a value outside your while loop. Take out your while loop. It's not necessary

public static double IsValid(double x)
{
    if (x > 0)
    {
        return x;
    }
    else
    {
        Console.WriteLine("Error: Please enter a positive value.");
        x = double.Parse(Console.ReadLine());
        return x;
    }
}
FlashOver
  • 1,855
  • 1
  • 13
  • 24
Alfredo A.
  • 1,697
  • 3
  • 30
  • 43
0

If you want to loop until the user gets it right, consider something like this:

 public static double GetPositiveNumber()
 {
     while (true)
     {
         Console.Write("Enter a Positive number: ");
         var response = Console.ReadLine();
         if (!double.TryParse(response, out var doubleValue))
         {
             Console.WriteLine("You must enter a valid number");
             continue;     //causes control to jump to the end of the loop (and back again)
         }

         if (doubleValue > 0)
         {
             return doubleValue;     //The only exit to the loop
         }
         //if I get here, it's a valid number, but not positive
         Console.WriteLine("Sorry, the number must be positive...");
     }
 }
Flydog57
  • 6,851
  • 2
  • 17
  • 18