public class Reverser Demonstrate a method that returns an
public class Reverser
{
// Demonstrate a method that returns an array
public static int[] reverse(int[] a)
{
int[] newArray = new int[a.length];
for (int i = 0; i < a.length; i++)
newArray[(a.length-1) - i] = a[i];
// fill newArray from end to beginning
return newArray;
}
// TODO: write a void method reverse2 that reverses
// an array in place by changing its contents
// this can be done with a for loop or by reusing
// the reverse method to create a new reversed
// array and then copying its contents into the
// original array; test that this works in main
private static void display(String header, int[] a)
{
if (header.length() != 0)
System.out.print(header + \" \");
for (int i = 0; i < a.length; i++)
System.out.print(a[i] + \" \");
System.out.println();
System.out.println();
}
public static void main(String[] args)
{
int[] example = { 0, 1, 2, 3, 4, 5 };
display(\"Before reversing:\", example);
example = reverse(example);
// change the array that example refers to
display(\"After reversing: \", example);
// write a test for reverse2 here
}
}
------------------------------------------------------
Copy Reverser.java, containing the reverse method, to Reverser2.java and write and test a reverse2() method:
------------------------------------------------------
reverse2 should have
the following header:
public
static void reverse2(int[] a)
------------------------------------------------------
reverse2 should reverse
the array a passed into the method in place, that is, it will not
return a new array, but instead will replace the contents of the original array
with its same items, but in reverse order.
-------------------------------------------
Hints: there are at
least two possible ways to approach this:
Simple: Use reverse() to create a new array
with the a array’s elements in reverse order, and copy them into a
Complex: Use a for loop as in reverse(),
but only go through ½ of the a array, and swap elements from start to
end (you might want to write a swap() method to help with this)
Solution
Please find the required program along with its output. Please see the comments against each line to understand the step.
----------------------------------------------------
OUTPUT:
Before reversing: 0 1 2 3 4 5
After reversing: 5 4 3 2 1 0
Before reversing: 0 1 2 3 4 5
After reversing: 5 4 3 2 1 0
![public class Reverser { // Demonstrate a method that returns an array public static int[] reverse(int[] a) { int[] newArray = new int[a.length]; for (int i = 0; public class Reverser { // Demonstrate a method that returns an array public static int[] reverse(int[] a) { int[] newArray = new int[a.length]; for (int i = 0;](/WebImages/1/public-class-reverser-demonstrate-a-method-that-returns-an-969577-1761495728-0.webp)