Hackathon III

The purpose of this assignment is to deepen your understanding of array manipulation in Java. You will be using a provided Java class named ArrayTest that contains several static methods designed to perform different operations on arrays.Here are the 5 static methods you need to design:

  • public static int sumArray(int[] array): Returns the sum of all elements in an integer array.

  • public static int largestNumber(int[] array): Finds and returns the largest number in an integer array.

  • public static String longestString(String[] array): Identifies and returns the longest string in a string array.

  • public static int[] reverseArray(int[] array): Returns a new array that is the reverse of the given integer array.

  • public static int[] shiftArray(int[] array): Shifts the elements of an integer array by one position and returns the result.

  • public static int[] consolidate(int[] array): put all the zero elements to the end of the array.

For example, if the array is {1, 3, 0, 2, 4, 0, 5}, consolidate will return a new array as: {1, 3, 2, 4, 5, 0, 0}.The order of the non-zero is the same as before the consolidation.

Method Call

Return

Explanation

int[] x = {1,2,3,4,5};

Create an integer array.

String[] y = {"hello", "world", "Java", "programming"};

Create an String array.

sumArray(x);

15

Sum of the elements {1, 2, 3, 4, 5} is 15.

largestNumber(x);

5

The largest number in the array {1, 2, 3, 4, 5} is 5.

longestString(y);

"programming"

The longest string in {"hello", "world", "Java", "programming"} is "programming".

reverseArray(x);

{5, 4, 3, 2, 1}

The reverse of {1, 2, 3, 4, 5} is {5, 4, 3, 2, 1}.

shiftArray(x);

{2, 3, 4, 5, 1}

Shifting elements of {1, 2, 3, 4, 5} by one position results in {2, 3, 4, 5, 1}.

int[] z = {1, 3, 0, 2, 4, 0, 5}; consolidate(z);

{1, 3, 2, 4, 5, 0, 0}

Put zero elements to the end of the array while maintaining the same order of non-zero values.

To test the methods in the ArrayTest class, please add the examples above main method. For methods that return an integer or String, use System.out.println to display the result. For methods that return an array, iterate through the array and print each element in one line. After print all elements, print another line.

Here is an example:

System.out.println(ArrayTest.largestNumber(x)); //print an integer

int[] reversedArray = ArrayTest.reverseArray(x); 
for (int num : reversedArray) {    //print an array
  System.out.print(num + " ");
}
System.out.println();  //print another line

Last updated