问题
I'm working with arrays and methods. I'm working on writing a code that will calculate the average of numbers entered by user in an array. I came up with the first method but VS tells me that "not all code paths return a value". When I tested the code in the Main() method it works well but when it's inside my GetValues() method i get the error.
I read all other posts but they not quite make sense to me because of their specificity. I know this isn't too difficult but I'm a beginner and trying to understand this myself.
My program isn't done yet, the following code is just the first part (method) of my program. Once GetValues () work, the idea is then to call this method from another method that will calculate the average. Again, GetValues() is supposed to capture the array.
Here's the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace testscores
{
class Program
{
static void Main(string[] args)
{
}
private static int[] GetValues()
{
string inValue;
int[] score = new int[5];
int total = 0;
for (int i = 0; i < score.Length; i++)
{
Console.Write("Enter Score {0}: ", i + 1);
inValue = Console.ReadLine();
score[i] = Convert.ToInt32(inValue);
}
for (int i = 0; i < score.Length; i++)
{
total += score[i];
}
}
}
}
回答1:
Are you trying to return the integer array score
?
....
for (int i = 0; i < score.Length; i++)
{
total += score[i];
}
return score;
}
So you can capture this array when you call it like so
int[] scores = GetValues();
回答2:
Your function is declared to return int[]
but there is no single return
statement within it.
回答3:
At the end of your function GetValues() you need to return an int[]. Which is what the compiler error is telling you; if you follow all code paths in GetValues(), there is at least ONE that does not return a value. (add return score
to the end of the function).
回答4:
Your method is not returning anything and is not declared void, but int[]
回答5:
The compiler error is because you need to add a return score
Beyond that, you're also doing a loop to populate the local variable 'total', and then doing nothing with that which seems like a design/logic error. Basically that code can just be removed unless you make total a member of the class or out param instead of local variable. You could also just be doing this in the first loop.
来源:https://stackoverflow.com/questions/7936615/not-all-code-paths-return-a-value