Admin Lost Admin Lost - 2 months ago 318
Java Question

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

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?

Answer

Since only the ends need to be swapped, and this swap need to happen exactly once (not repeatedly), how about:

  // Why do you need yo swap it in a cycle, thus many times???
  /* Commenting faulty code out
  for (i = 0; i < numElem; ++i) {
     tmpStore = sortArray[i]; // Do swap
     sortArray[i] = sortArray[numElem - 1];
     sortArray[numElem - 1] = tmpStore;
  }
  */

  // A single time should do
  tmpStore = sortArray[0]; // Do swap with the starting end
  sortArray[0] = sortArray[numElem - 1];
  sortArray[numElem - 1] = tmpStore;

(note: I think I'm getting tired of inane comments/answers sending a beginner on fool's errands)

Comments