ユーザー入力をチェックし、検証に合格した場合にのみ入力を返すメソッドを開発しようとしています。
これが私がやりたいことです:
- ユーザーが入力する
- 入力値の確認
- 入力がロジックを満たす場合はその値を返し、そうでない場合は関数を再度呼び出します。
これは本当に私が欲しいものですが、コンパイラは次のように述べてい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 以外の値を入力してから有効な数値を入力した場合、プログラムは次のことを行います。
- 入力を返します。
- 子 if ステートメントにジャンプして UserInput(); を実行します。
- その後 -1 を返します。