Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Modern Database Management

Authors: Jeff Hoffer, Ramesh Venkataraman, Heikki Topi

12th edition

133544613, 978-0133544619

Students also viewed these Databases questions