Question

public static void reversedArray(double testArray[])
{
    double lastNumber = 0;
    for (int counter1 = 0, counter2 = testArray.length - 1; counter1 < testArray.length; counter1++, counter2 \--)
    {
       lastNumber = testArray[counter2];
       testArray[counter1] = testArray[counter2];
       testArray[counter2] = lastNumber;
    }
}

This is the method that reverses the array. The array is a length of 5. It correctly displays the first 3 numbers, but the last 2 numbers are wrong. E.g., I enter 1,2,3,4,5 and it returns 5,4,3,4,5

Edit: Looks like I got it, I took out the testArray.length as the comparison in the for loop and replaced it with counter2.

Was it helpful?

Solution

You are overwriting data in your array. You need some temporary location to store it. Now you should be able to fix your method yourself.

Next time consider to use Collections.reverse(Arrays.asList(yourArray)) instead of writing it by your own.

OTHER TIPS

Should be

  lastNumber = testArray[counter2];
  testArray[counter2] = testArray[counter1];
  testArray[counter1] = lastNumber;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top