[英]Return error: not all code paths return a value
我正在嘗試開發一種方法來檢查用戶輸入,並且僅在通過驗證時才返回輸入。
這就是我想要做的:
這確實是我想要的,但編譯器聲明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 的值,然后輸入一個有效數字,則程序將執行以下操作:
您需要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.