Reputation: 77
I am getting index is out of bounds at lines 33 and 46. Why is this? I am trying to reverse the array. I know what the error code means, but I do not know why I am getting it. Line 33 - string reversed = ReverseArray(crafting); Line 46 - return reverseCraft[5];
//make an array to be reversed
string[] craftArray = new string[5] { "Iron", "Stone", "Copper", "Steel", "Clay" };
//create a variable to hold return value
string[] crafting = new string[5];
//function call the ReverseCraft method
string reversed = ReverseArray(crafting);
//Report the calculation to the user
Console.Write("The array reversed is" + reversed);
}
public static string ReverseArray(string[] craft)
{
//create a variable and reverse
string[] reverseCraft = new string[5] { craft[4], craft[3], craft[2], craft[1], craft[0] };
//return value
return reverseCraft[5];
}
}
}
Upvotes: 0
Views: 53
Reputation: 1374
It's throwing an error on the line
return reverseCraft[5];
because there is no reverseCraft[5].
The first element of reverseCraft is reverseCraft[0] and the last element is reverseCraft[4].
Upvotes: 0
Reputation: 726849
Your reverse method has a wrong signature. It should return string[]
, like this:
public static string[] ReverseArray(string[] craft) {
//create a variable and reverse
string[] reverseCraft = new string[5] { craft[4], craft[3], craft[2], craft[1], craft[0] };
//return value
return reverseCraft;
}
With this code in place, all you need to do is print the result properly:
string[] reversed = ReverseArray(crafting);
//Report the calculation to the user
Console.Write("The array reversed is " + string.Join(", ", reversed));
Upvotes: 2