【问题标题】:Return error: not all code paths return a value返回错误:并非所有代码路径都返回值
【发布时间】:2012-04-06 02:42:17
【问题描述】:

我正在尝试开发一种方法来检查用户输入,如果输入通过验证,返回。

这就是我想做的:

  1. 用户输入输入
  2. 检查输入值
  3. 如果输入满足逻辑,则返回该值,否则再次调用该函数。

真的是我想要的,但编译器声明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; 
   }
}

但是,这是满足编译器的以下代码。

    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;

       }
    }

这种工作,但我得到奇怪的结果。如果用户在第一次输入时输入 input,即 1、2、3 或 4(即 if 语句计算为 false),则返回的输入就是用户输入的任何内容。但是,如果用户输入的值 不是 1、2、3 或 4 然后输入一个有效数字,那么程序将执行以下操作:

  1. 返回输入;
  2. 跳转到子if语句并运行UserInput();
  3. 然后返回 -1。

【问题讨论】:

    标签: c#


    【解决方案1】:

    从外观上看,您需要 return UserInput();。它看起来就像一个recursive function,它将通过不断地调用自身直到满足一个令人满意的约束来向下钻取并返回底部。

    您正在做的是向下钻取,让它返回一个值,然后在此之上返回一个 -1。

    您还通过再次检查输入来复制自己。看来这可以归结为以下几点:

    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): ");
           return UserInput();
       }
       else
           return input;
    }
    

    所以,如果用户输入了一个无效的号码,它会再次调用自己。如果他们然后输入一个有效的数字。该方法将返回到第一个调用,该调用将获取该值并将其返回到原始调用。

    下面是使用 this 的递归调用的样子:

    CallingMethod calls UserInput(0)
    -UserInput(0)
    --UserInput(5)
    ---UserInput(2) return 2
    --UserInput(5) return 2
    -UserInput(0) return 2
    CallingMethod receives and uses 2
    

    【讨论】:

    • 非常感谢,不知道你可以返回一个函数。
    • @dgamma3 是的,这是一种类似这样的截断方式: int returnValue = UserInput();返回返回值; .....这基本上就是它正在做的事情。它不是返回一个函数,而是返回函数的返回值
    【解决方案2】:

    为什么不简化为以下(不需要 else 语句或第二个 if)。还要注意递归调用应该返回以使其正常工作:

    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): ");
           return UserInput(); //<--- problem was here
       }
       return input; 
    }
    

    【讨论】:

    • 不需要第二个if (input &lt; 1 || input &gt; 4)
    猜你喜欢
    • 2013-07-01
    • 2014-04-16
    • 2015-02-07
    • 2012-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    相关资源
    最近更新 更多