所以基本上我試圖做一個測驗遊戲,這個子程序檢查答案是否正確。基本上每次我嘗試運行程序時都會給我一個錯誤,即並不是所有的代碼路徑都返回一個值,即使它清楚地看到有一個返回值爲真;並返回錯誤;聲明在最後。繼續收到錯誤「不是所有的代碼路徑都返回一個值」
private bool CheckIfCorrect(byte questionNum, string answers, string userAnswer)
{
int adjustmentToTheScore;
const int EASY_QUESTION_5 = 1;
const int MEDIUM_QUESTION_10 = 2;
const int HARD_QUESTION_15 = 3;
const int GENERALPOINTS = 100;
if (userAnswer == "A" || userAnswer == "B" || userAnswer == "C" || userAnswer == "D")
{
if (answers == userAnswer)
{
if (questionNum <= EASY_QUESTION_5)
{
adjustmentToTheScore = (EASY_QUESTION_5 * GENERALPOINTS/totalTimePassed);
userScore += adjustmentToTheScore;
}
else if (questionNum <= MEDIUM_QUESTION_10)
{
adjustmentToTheScore = (MEDIUM_QUESTION_10 * GENERALPOINTS/totalTimePassed);
userScore += adjustmentToTheScore;
}
else if (questionNum <= HARD_QUESTION_15)
{
adjustmentToTheScore = (HARD_QUESTION_15 * GENERALPOINTS/totalTimePassed);
userScore += adjustmentToTheScore;
}
rightAnswerCount++;
goalSound.SoundLocation = "Goal_Sound.wav";
goalSound.Play();
lblTotalCorrect.Text = Convert.ToString(rightAnswerCount);
if (fastestAnswer == 0 || totalTimePassed < fastestAnswer)
{
fastestAnswer = totalTimePassed;
lblFastestAnswer.Text = Convert.ToString(fastestAnswer) + "(s)";
}
else
{
adjustmentToTheScore = 10;
userScore = userScore - adjustmentToTheScore;
booing.SoundLocation = "Booing.wav";
booing.Play();
}
lblScore.Text = "Score: " + Convert.ToString(userScore);
return true;
}
else
{
MessageBox.Show("Invalid answer please put a, b, c or d!");
return false;
}
}
}
}
}
嵌套減少代碼的可讀性,壞習慣這種方式代碼..靜態代碼分析工具會爲您提供建議,以便改進您的代碼... [請參閱此處](http://stackoverflow.com/questions/268132/invert-if-statement-to-reduce-nesting)關於此場景的一些好的討論。 – felickz