数组逆序输出实现求助:现有代码仅输出原数组
Hey Tyler, I see exactly where the problem is! Right now, your code is doing tempArray[i] = A[i] inside that reverse loop—which just copies each element from the original array to the same position in the temp array. No wonder it's printing the original array instead of the reversed one!
You were spot-on about needing two indices: one to track the decreasing position in the original array (starting from the last element) and another to track the increasing position in the temp array (starting from the first element). Here's how to implement that smoothly:
Corrected Code
static void reverseArray(int [] A) { int[] tempArray = new int[A.length]; // Use A.length instead of hardcoding 10 for flexibility // Use two indices to map original array's end to temp array's start for(int originalIndex = A.length - 1, tempIndex = 0; originalIndex >= 0; originalIndex--, tempIndex++) { tempArray[tempIndex] = A[originalIndex]; } printArray(tempArray); // Print the properly reversed temp array }
Breakdown of the Fix
- We swapped the hardcoded
10withA.lengthso the method works for any size array, not just 10 elements (a solid practice for reusable code!). - The
forloop now uses two variables in sync:originalIndexstarts at the last element ofA(A.length - 1) and counts backward.tempIndexstarts at the first element oftempArray(0) and counts forward.
- Each iteration takes the current end element from
Aand drops it into the current start position oftempArray—this is what actually flips the order of elements!
Alternative Approach (Single Index)
If you prefer a simpler loop structure with just one index, you can calculate the reversed position mathematically:
static void reverseArray(int [] A) { int[] tempArray = new int[A.length]; for(int i = 0; i < A.length; i++) { // Grab the element from the opposite end of the original array tempArray[i] = A[A.length - 1 - i]; } printArray(tempArray); }
This works because for each index i in the temp array, we pull the element from A that's at the mirror position (e.g., when i=0, we take A[9] for a 10-element array; when i=1, we take A[8], and so on).
Either way, both approaches create a reversed copy of the original array without modifying A itself—exactly what you needed!
内容的提问来源于stack exchange,提问作者Tyler P

