簡體   English   中英

返回錯誤:並非所有代碼路徑都返回值

[英]Return error: not all code paths return a value

我正在嘗試開發一種方法來檢查用戶輸入,並且在通過驗證時才返回輸入。

這就是我想要做的:

  1. 用戶輸入
  2. 檢查輸入值
  3. 如果輸入滿足邏輯,則返回該值,否則再次調用 function。

確實是我想要的,但編譯器聲明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是第一個 go 中的 1、2、3 或 4(即if語句求值為false ),則返回的輸入是用戶輸入的任何內容。 但是,如果用戶要輸入一個不是1、2、3 或 4 的值,然后輸入一個有效數字,則程序將執行以下操作:

  1. 返回輸入;
  2. 跳轉到子 if 語句並運行 UserInput();
  3. 然后返回-1。

您需要return UserInput(); 從它的外觀來看。 它看起來就像一個 遞歸的 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;
}

因此,如果用戶輸入了無效號碼,將會發生什么情況,它會再次呼叫自己。 如果他們隨后輸入有效號碼。 該方法將返回到第一次調用,它將獲取該值並將其返回到原始調用。

這是使用它的遞歸調用的樣子:

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

為什么不簡化為以下內容(不需要 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; 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM