1

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

这就是我想要做的:

  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。
4

2 回答 2

6

你需要return UserInput();通过它的外观。它只是看起来像一个递归函数,它将通过不断调用自身直到满足满意的约束来向下钻取并返回底部。

您正在做的是向下钻取,让它返回一个值,然后在此之上返回一个 -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
于 2012-04-06T02:44:20.083 回答
1

为什么不简化为以下(不需要 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; 
}
于 2012-04-06T02:45:35.373 回答