In: Computer Science
FOR JAVA (ZYBOOK) 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}.
I can't modify/change any of the code. I can only add code to implement this where it says /* Your solution goes here */.
This is the code:
import java.util.Scanner;
public class ModifyArray {
/* Your solution goes here */
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
int numElem = 4;
int[] sortArray = new int[numElem];
int i;
int userNum;
for (i = 0; i < sortArray.length; ++i) {
sortArray[i] = scnr.nextInt();
}
swapArrayEnds(sortArray);
for (i = 0; i < sortArray.length; ++i) {
System.out.print(sortArray[i]);
System.out.print(" ");
}
System.out.println("");
}
}
import java.util.Scanner; public class ModifyArray { /* Your solution goes here */ private static void swapArrayEnds(int[] sortArray) { // Storing first element to tmp int tmp = sortArray[0]; // Replacing first element to last element sortArray[0] = sortArray[sortArray.length-1]; // Replacing last element with value of variable tmp sortArray[sortArray.length-1] = tmp; } public static void main (String [] args) { Scanner scnr = new Scanner(System.in); int numElem = 4; int[] sortArray = new int[numElem]; int i; int userNum; for (i = 0; i < sortArray.length; ++i) { sortArray[i] = scnr.nextInt(); } swapArrayEnds(sortArray); for (i = 0; i < sortArray.length; ++i) { System.out.print(sortArray[i]); System.out.print(" "); } System.out.println(""); } }