82.0k views
3 votes
Six integers are read from input and stored into the array arrayToModify. Write a static method swapFirstTwo() that takes an integer array parameter and swaps the first element with the second element of the array.

Ex: If the input is 30 95 60 10 35 5, then the output is:

Initial array: 30 95 60 10 35 5
Final array: 95 30 60 10 35 5
GIVEN CODE (cannot be modified):

import java.util.Scanner;

public class ArrayMethods {

/* Your code goes here */

public static void printArr(int[] arr) {
int i;

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

public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
final int NUM_ARRAY = 6;
int[] arrayToModify = new int[NUM_ARRAY];
int i;
int userNum;

for (i = 0; i < arrayToModify.length; ++i) {
arrayToModify[i] = scnr.nextInt();
}

System.out.print("Initial array: ");
printArr(arrayToModify);

swapFirstTwo(arrayToModify);

System.out.print("Final array: ");
printArr(arrayToModify);
}
}

User Lsabi
by
8.0k points

1 Answer

4 votes

Final answer:

The student's question involves creating a method to swap the first two elements of an integer array in Java. The solution contains a check for the array size and performs a swap using a temporary variable to store the value of the first element before exchanging the values of the first and second elements.

Step-by-step explanation:

The student has requested help in writing a static method in Java that swaps the first two elements of an integer array. The method is called swapFirstTwo() and will be integrated into an existing program structure where integers are read into an array named arrayToModify. It's a simple task that involves manipulating array indices.

To perform the swap, we identify the first (at index 0) and second elements (at index 1) and exchange their values. This operation can be achieved with the help of a temporary variable, or by using a succinct swap operation involving array destructuring in languages that support it (though not possible in Java).

Example Method

public static void swapFirstTwo(int[] arr) {
if (arr.length < 2) { // Check if the array has fewer than two elements
return; // Do nothing if there are not enough elements to swap
}
int temp = arr[0]; // Store the first element in a temporary variable
arr[0] = arr[1]; // Assign the value of the second element to the first
arr[1] = temp; // Assign the value of the temporary variable to the second
}

After the swapFirstTwo() method is executed on the example input (30 95 60 10 35 5), the output will demonstrate that the originally first and second elements (30 and 95) have been swapped in the modified array.

User Mthecreator
by
8.7k points