Linked Questions

Popular Questions

What am I missing in order to swap numbers in this array? Java

Asked by At

So in my assignment, I'm halfway of solving this particular java array (this is an online book; percentage is at 50% in testing phase). However I cannot figure out what I'm missing. For this code, I have to make the input reverse two numbers (of whatever amount is requested). I tried looking online for similar situation but none answered what I needed.

Directions: Write a method swapArrayEnds() that swaps the first and last elements of its array parameter. Ex: sortArray = {10, 20, 30, 40} becomes {40, 20, 30, 10}. The array's size may differ from 4.

import java.util.Scanner;

public class ModifyArray {
// ANYTHING ABOVE THIS COMMENT CANNOT BE MODIFIED
   public static void swapArrayEnds(int[] sortArray, int numElem) {
      numElem = 4;
      int i = 0;         // Loop index
      int tmpStore = 0;  // Temp variable for swapping

      for (i = 0; i < numElem; ++i) {
         tmpStore = sortArray[i]; // Do swap
         sortArray[i] = sortArray[numElem - 1];
         sortArray[numElem - 1] = tmpStore;
      }

      return;
   }
// ANYTHING BELOW THIS COMMENT CANNOT BE MODIFIED
   public static void main (String [] args) {
      int numElem = 4;
      int[] sortArray = new int[numElem];
      int i = 0;

      sortArray[0] = 10;
      sortArray[1] = 20;
      sortArray[2] = 30;
      sortArray[3] = 40;

      swapArrayEnds(sortArray, numElem);

      for (i = 0; i < numElem; ++i) {
         System.out.print(sortArray[i]);
         System.out.print(" ");
      }
      System.out.println("");

      return;
   }
}

At the moment, my error code is:

Testing with original sortArray = {10, 20, 30, 40}
Expected output:  40 20 30 10 
Your output:  40 10 20 30 
Tests aborted.

I'm not sure how my input became like that, but it merely placed the original last number in front of the original first. How do I have it that the first and last numbers are swapped?

Related Questions