我已经编写了这个函数,将其用于另一个类,但是代码生成了一个错误,并说:不是所有的代码路径都返回值。我也试着去寻找这个问题的解决方案,但大多数的答案都与实际问题无关。希望能碰到对这类错误的逻辑理解。
using System;
namespace Practice
{
class ContinueAgain
{
public int Continue() // (Not all code paths return a value)
{
rerun:
try {
char chAgain;
// user guiding message and then taking input
Console.WriteLine("nAgain? (y/n)n");
chAgain = char.Parse(Console.ReadLine());
// filtering the condition if the user wants to continue or not
// exiting out of the method if user selects 'Y'/'y'
if (chAgain == 'y' || chAgain == 'Y') // if block begins
{
return 1;
}
// exiting out of the method if user selects 'N'/'n'
else if (chAgain == 'n' || chAgain == 'N')
{
Console.WriteLine("nThank you for using :)n");
return 0;
}
// printing user message if user enters any input apart from the asked input
if(chAgain!='y' || chAgain!='Y' || chAgain!='n' || chAgain!='N')
{
Console.WriteLine("nThis input in invalidn");
goto rerun;
}
#endregion if block 4 - ends
} // try block ends
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
想知道是什么导致或触发了这个错误事件。
您需要在catch
块内和try
块末尾返回一个值。
您的代码中缺少2个返回语句-在最后一个if
语句之后和在catch
块