Question: Complete 3 different overloaded slice() methods in the Sequence class (attached to Project 01). The slice() method works on arrays much like the substring() method

Complete 3 different overloaded slice() methods in the Sequence class (attached to Project 01). The slice() method works on arrays much like the substring() method does on Strings. There are three possible versions.

int[] slice(int start);

int[] slice(int start, int end);

int[] slice(int start, int end, int step);

If start is negative, then it calculated from the end of the array. Given the Sequence object:

Sequence seq = new Sequence(new int[]{1, 2, 3, 4, 5});

Then seq.slice(3) returns {4, 5}, while seq.slice(-1) returns {5}. Notice that when two arguments are supplied they are the starting index and the index that is one past the last index. If only one argument is supplied, it is the starting index. When a third argument is provided, it is the step value, meaning how much to increment/decrement each time. For instance, seq.slice(0, 5, 2) returns the array {1, 3, 5}.

Sequence Code:

public class Sequence { private int[] mArray; /** * Constructs a sequence of integers. * @param array the array to initialize the sequence. */ public Sequence(int[] array) { mArray = array.clone(); } // TODO: Write the three versions of slice() here @Override public String toString() { String result = "{"; if (mArray.length > 0) { result += mArray[0]; for (int i = 1; i < mArray.length; i++) { result += ", " + mArray[i]; } } return result + "}"; } public static void main(String[] args) { Sequence a = new Sequence(new int[]{1, 2, 3, 4, 5}); // some informal testing // System.out.println("a.slice(0)->" + a.slice(0)); // System.out.println("a.slice(1)->" + a.slice(1)); // System.out.println("a.slice(-1)->" + a.slice(-1)); // System.out.println("a.slice(-2)->" + a.slice(-2)); // System.out.println("a.slice(5)->" + a.slice(5)); // System.out.println("a.slice(-5)->" + a.slice(-5)); // System.out.println("a.slice(0, 5, 2)->" + a.slice(0, 5, 2)); // System.out.println("a.slice(1, 5, 2)->" + a.slice(1, 5, 2)); // System.out.println("a.slice(1, 5, 3)->" + a.slice(1, 5, 3)); // System.out.println("a.slice(2, 5, 3)->" + a.slice(2, 5, 3)); // System.out.println("a.slice(-1, -6, -1)->" + a.slice(-1, -6, -1)); } } 

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!