int search(string [][]mat, int n, string x){
//set indexes for top right element
for(int i = 0; i<n; i++)
{
for(int j = n-1; j>=0; j--)
{
if ( mat[i][j] == x )
{
Debug.Log(x +""+"Found at "+i +" "+j);
// int[] n2 = new int[] {2, 4, 6, 8};
// int [] xyz = new int [] {i, j};
return i;
}
}
}}
如何摆脱此错误:并非所有代码路径都返回值?
Error:
*Assets/Scripts/Chess/Bishop.cs(237,22):错误 CS0161:`Bishop.search(string[][], int, string)':并非所有代码路径都返回值*
弄清楚如果你找不到的话你想要发生什么x
,并在方法结束时返回该值。例如:
// Fixed naming conventions and indentation...
// Why do we need n here at all? Why not just use the length of the array?
int Search(string[][] mat, int n, string x)
{
//set indexes for top right element
for (int i = 0; i < n; i++)
{
// Why are we looking backwards here?
for (int j = n - 1; j >= 0; j--)
{
if (mat[i][j] == x)
{
// More readable formatting...
Debug.Log(string.Format("{0} found at {1}, {2}", x, i, j));
return i;
}
}
}
// Not found: return -1 to indicate failure. Or you could throw an exception
return -1;
}
更一般地说:编译器错误消息在这里相当清楚 - 有一种方法可以让您在不返回任何内容的情况下到达方法的末尾。值得退后一步并尝试思考为什么你自己无法解决这个问题。您是否对编译器错误消息足够重视?您是否考虑过该方法在所有情况下可能执行的所有操作?下次你怎样才能更好地处理这个问题?
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)