65,808 views
8 votes
8 votes
define a method named swapvalues that takes an array of four integers as a parameter, swaps array elements at indices 0 and 1, and swaps array elements at indices 2 and 3. then write a main program that reads four integers from input and stores the integers in an array in positions 0 to 3. the main program should call function swapvalues() to swap array's values and print the swapped values on a single line separated with spaces. ex: if the input is: 3 8 2 4 function swapvalues() returns and the main program outputs: 8 3 4 2 the program must define and call a method: public static void swapvalues(int[] values)

User Amin Abdolrezapoor
by
3.0k points

2 Answers

17 votes
17 votes

Final answer:

To swap values in an array, create a method called swapvalues that takes an array of four integers as a parameter. In this method, swap the values at indices 0 and 1, and then swap the values at indices 2 and 3. Then, in the main program, read four integers from input, store them in an array, call the swapvalues method, and print the swapped values.

Step-by-step explanation:

To define the method swapvalues, we can create a function that takes an array of four integers as a parameter. Within this function, we can use a temporary variable to swap the values at indices 0 and 1, and then swap the values at indices 2 and 3. Here is an example of the swapvalues method:

public static void swapvalues(int[] values) {
int temp = values[0];
values[0] = values[1];
values[1] = temp;
temp = values[2];
values[2] = values[3];
values[3] = temp;
}

In the main program, you can read four integers from input and store them in an array. Then, call the swapvalues method with the array as an argument. Finally, print the swapped values on a single line, separated by spaces. Here is an example of the main program:

public static void main(String[] args) {
int[] array = new int[4];
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 4; i++) {
array[i] = scanner.nextInt();
}
swapvalues(array);
for (int i = 0; i < 4; i++) {
System.out.print(array[i] + " ");
}
}

User Marvin Klar
by
2.7k points
19 votes
19 votes

Answer:

Step-by-step explanation:

e

User Phoet
by
3.2k points