Problem Set 2
due by 11:59 p.m. on Tuesday, June 3, 2025
Preliminaries
In your work on this assignment, make sure to abide by the collaboration policies of the course.
If you have questions while working on this assignment, please
come to office hours, post them on Piazza, or email cs112-staff@cs.bu.edu
.
Make sure to follow the instructions outlined at the end of Part I and Part II when submitting your assignment.
Part I
53 points total
This part of the assignment consists of a series of short-answer questions. You will be able to check your answers to at least some of these questions by executing the code, but we strongly encourage you to answer them on your own and to convince yourself of the correctness of your answers before you try to test them. These questions are similar to ones that could appear on the midterms and final exam, so it’s important to be able to answer them without the use of a computer.
Creating the necessary folder
-
If you haven’t already created a folder named
cs112
for your work in this course, follow these instructions to do so. -
Then create a subfolder called
ps2
within yourcs112
folder, and put all of the files for this assignment in that folder.
Creating the necessary file
Problems in Part I will be completed in a single PDF file. To create it, you should do the following:
-
Access the template that we have created by clicking on this link and signing into your Google account as needed.
-
When asked, click on the Make a copy button, which will save a copy of the template file to your Google Drive.
-
Select File->Rename, and change the name of the file to
ps2_partI
. -
Add your work for the problems from Part I to this file.
-
Once you have completed all of these problems, choose File->Download->PDF document, and save the PDF file in your
ps2
folder. The resulting PDF file (ps2_partI.pdf
) is the one that you will submit. See the submission guidelines at the end of Part I.
Problem 1: String
objects and their methods
9 points total; individual-only
Working with strings: Python vs. Java
Python has built-in operators and methods for common string
operations like indexing and slicing. In addition, string objects —
like all objects — have methods inside them. These methods allow you
to obtain information about a string and to create new strings that
are based on the original one.
Java lacks many of Python’s built-in operators and functions for strings. Instead, most operations involving strings – including indexing and slicing – are done using methods that are inside the string object.
The table below compares the ways in which some common string operations would be accomplished in Python and Java:
operation |
in Python |
in Java |
---|---|---|
assigning to a variable (and, in Java, declaring the variable) |
|
|
concatenation |
|
|
finding the number of characters |
|
|
indexing |
|
|
slicing |
|
|
converting all letters to uppercase |
|
|
converting all letters to lowercase |
|
|
determining if a substring is in a string |
|
|
finding the index of the first occurrence of a character or substring |
|
|
testing if two strings are equivalent |
|
|
Notes:
-
Recall that Java has a separate type called
char
for values that consist of a single character. Literals of this type are surrounded by single quotes (e.g., the'o'
in the calls1.indexOf('o'))
, whereas string literals must be surrounded by double quotes. (In Python, there is no separatechar
type, and string literals can be surrounded by either single or double quotes.) -
The
charAt()
method that we use for indexing in Java returns a value of typechar
. For example, the calls1.charAt(0)
in the table above would return thechar
value'B'
, since'B'
is the first character in the string"Boston"
.
Given the information above, here are the tasks you should perform:
-
(0 points) To ensure that you understand how the above string operations work in Java, we strongly encourage you to write a simple program to experiment with them.
For example, you could put the following lines in the
main
method of a test program:String s1 = "Boston"; System.out.println( s1.substring(1, 4) );
Doing so should display the result of the expression being printed:
ost
-
(6 points) Assume that the following statements have already been executed:
String s1 = "don't string"; String s2 = "me along!";
For each of the following values, construct an expression involving operations on
str1
and/orstr2
that evaluates to that value. For full credit, you should not use literal values (e.g.,"T"
or'e'
) unless it is absolutely necessary to do so.-
Construct an expression involving
s1
and/ors2
that produces the following value:"string me"
We have given you the answer to this part of the problem in
ps2_partI
.Important: Note that the provided answer is a single expression that produces the necessary value. The answer does not use any assignment statements or print statements. Your answers to each of the remaining parts of this question should also consist of just a single expression.
-
Construct an expression involving
s1
and/ors2
that produces the following value:"sing along"
-
Construct an expression involving
s1
and/ors2
that produces the following value:"DING!"
Hint: One or more parts of your expression will need to chain two method calls together – i.e., to do something that looks like this:
str2.toLowerCase().substring(9)
-
Construct an expression involving
s1
and/ors2
that produces the following value:"dime"
-
Construct an expression involving
s1
and/ors2
that produces the following value:'r'
Note that the single quotes mean that you must produce a
char
, not aString
. See the notes under the table above that discuss thechar
type. -
Construct an expression involving
s1
and/ors2
that produces the following value:"r"
Note that the double quotes mean that you must produce a
String
, not achar
. -
Construct an expression involving
s1
and/ors2
that produces the following value:"dm"
-
Construct an expression involving
s1
and/ors2
that produces the following value:9
Hint: Use the
indexOf
method to find a character ins1
ors2
. -
Construct an expression involving
s1
and/ors2
that produces the following value:"don'u suring"
Use the first
replace
method in theString
class; consult the API of theString
class to figure out how to use it.
-
Problem 2: Understanding code that uses an array
10 points total; individual-only
-
(4 points) Consider the following static method, which operates on an array of integers:
public static void mystery(int[] values) { for (int i = 1; i < values.length; i += 2) { values[i] = values[i - 1]; // part 1: What does the array look like here, // for each value of the loop variable i? } values[0] = values[values.length - 1]; // part 2: What does the array look like here? }
Consider the following code fragment, which calls this method:
int[] arr = {0, 1, 2, 3, 4, 5, 6, 7}; mystery(arr);
In this section of
ps2_partI
, we’ve provided a table that you should complete to illustrate the execution of the loop during the above method call.We have started the table for you. The first row shows what the array looks like before the start of the
for
loop. For each value of the loop variablei
, include a row in the table that shows what the array looks like at the end of the iteration of the loop for that value ofi
. You may not need all of the rows of the table.(Note: You should write the value of
values
as an array literal that shows the current contents of the array, even though the variable itself actually holds a reference to the array.) -
(2 points) What does the array represented by
values
look like just before the call tomystery
returns? -
(4 points) After running the code fragment from part 1, we then execute the following statement:
System.out.println(Arrays.toString(arr)));
Do we see the original array, or do we see the changes made by the call to the
mystery()
method? Explain briefly why your answer makes sense.(Note: If you want to check your answer, you’ll need to import the
java.util
package at the top of your test class so that you can use theArrays.toString()
method.)
Problem 3: Arrays and memory diagrams
12 points; individual-only
In this problem, you will draw a series of diagrams that illustrate the execution of a program that operates on arrays. We will work on a similar problem in Lab 2, and you may find it helpful to review our solutions to that problem (which will be posted after all of the labs have been held) before continuing.
Consider the following Java program:
public class ArrayTest { public static void foo(int[] a, int[] b) { // part 2: what do things look like when we get here? for (int i = 0; i < a.length; i++) { a[i] *= 2; } int[] c = {2, 4, 6, 8}; b = c; // part 3: what do things look like when we get here? } public static void main(String[] args) { int[] a = {1, 2, 3, 4}; int[] b = a; int[] c = new int[b.length]; for (int i = 0; i < b.length; i++) { c[i] = b[i]; } // part 1: what do things look like when we get here? foo(a, c); // part 4: what do things look like when we get here? System.out.println(a[2] + " " + b[2] + " " + c[2]); } }
-
In this section of
ps2_partI
(see above), we have given you the beginnings of a memory diagram. On the stack (the region of memory where local variables are stored), we have included a frame for themain
method. Outside of the stack, we have included the array to which the variablea
refers, and we have used an arrow to represent the reference to that array that is stored in the variablea
.Complete the provided memory diagram so that it shows what things look like in memory just before the call to
foo()
.To do so, you should:
-
Click on the diagram and then click the Edit link that appears below the diagram.
-
Make whatever changes are needed to the diagram. Below the thick horizontal line, we have given you a set of extra components that you can use as needed by dragging them above the thick line and putting them in the correct position. You may not need all of the provided components.
-
You can also edit any of the values in an array by clicking on one of its cells and editing the text that is inside the cell.
-
Once you have made all of the necessary changes, click the Save & Close button.
-
-
In this section of
ps2_partI
, we have given you the beginnings of a memory diagram that you should complete to show what things look like in memory at the start of the execution offoo()
—just before its first statement is executed. -
In this section of
ps2_partI
, we have given you the beginnings of a memory diagram that you should complete to show what things look like in memory at the end of the execution offoo()
—just before it returns. -
In this section of
ps2_partI
, we have given you the beginnings of a memory diagram that you should complete to show what things look like in memory after the call tofoo()
has returned—just before theprint
statement executes inmain()
.Note: We have included a method frame for
foo
, but it may or not be needed in this diagram; you should delete it if you determine that it would no longer be present in memory.
To check your answers: Java Tutor is an online tool that allows you to step through the execution of a Java program and visualize its execution. We’ve included a link to it on our Resources page, or you can use this link: Java Tutor
Keep in mind that you could be asked to solve a similar problem on the exams, so you should only use Java Tutor after you have solved the problem on your own!
Problem 4: Two-dimensional arrays
10 points total; individual only
Overview
Two-dimensional arrays in Java are extremely similar to
two-dimensional lists in Python.
In Python, a 2-D list is a list of lists:
grid = [ [2, 4], [5, 7], [8, 1] ]
In the same way, a 2-D array in Java is an array of arrays:
int[][] grid = { {2, 4}, {5, 7}, {8, 1} };
(Note: When we declare a variable for a 2-D array, the type of the
elements is followed by two pairs of square brackets: int[][]
)
Here is a comparison of other key operations for 2-D sequences:
operation |
in Python |
in Java |
---|---|---|
determining the number of rows |
|
|
determining the number of elements in row r |
|
|
determining the number of columns in a rectangular grid/matrix (in which all rows have the same length) |
|
|
accessing the element at row r, column c |
|
|
Problems
Assume that you have a variable twoD
that refers to a
two-dimensional array of integers. Here is another example of such
an array:
int[][] twoD = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16} };
-
(2 points) Write an assignment statement that replaces the value of 10 in the above array with a value of 30.
-
(3 points) Write a code fragment that prints the values in the rightmost column of the array to which
twoD
refers. Print each value on its own line. For the array above, the following values would be printed:4 8 12 16
Make your code general enough to work on any two-dimensional array named
twoD
that has at least one value in each row. You may also assume that all rows intwoD
have the same number of elements. -
(5 points) Write a code fragment that prints the values in the diagonal of the array to which
twoD
refers – i.e., the values along a diagonal line from the upper-left corner to the lower-right corner. Print each value on its own line. For the array above, the following values would be printed:1 6 11 16
Make your code general enough to work on any rectangular two-dimensional array in which the dimensions are equal – i.e., the number of rows is the same as the number of columns.
Problem 5: Our Rectangle
class revisited
12 points total; individual-only
Recall the Rectangle
class that we defined in lecture. (The relevant
version of this class is available here.)
-
Consider a potential instance method named
shrink
that would take an integer value as a parameter and reduce both of the dimensions of aRectangle
by that value. For example, if aRectangle
‘s dimensions are 80 x 40, then calling theshrink
method with a parameter of 10 would give theRectangle
dimensions of 70 x 30.- (1 point) What type of instance method would
shrink
be, an accessor or mutator? - (2 points) Give an appropriate method header for this method, making sure to take into account the fact that the method is non-static. You do not need to define the body of the method.
- (1 point) What type of instance method would
-
Now consider a potential instance method named
diagonal
that would return the length of the rectangle’s diagonal as a real number. For example, if aRectangle
‘s dimensions are 30 x 40, then thediagonal
method would return 50.0.- (1 point) What type of instance method would
diagonal
be, an accessor or mutator? - (2 points) Give an appropriate method header for this method, making sure to take into account the fact that the method is non-static. You do not need to define the body of the method.
- (1 point) What type of instance method would
-
Consider the following client code — i.e., code from another class that uses a
Rectangle
object:Rectangle rect = new Rectangle(10, 20); System.out.println("width = " + rect.width); rect.width = rect.width + rect.height; System.out.println(rect);
Because our
Rectangle
class employs appropriate encapsulation, this code fragment will not compile.- (2 point) Explain what problems are present in the code fragment that prevent it from compiling.
- (4 points) Rewrite the fragment to eliminate those problems while maintaining the intended functionality of the original version.
Submitting your work for Part I
Note: There are separate instructions at the end of Part II that you should use when submitting your work for that part of the assignment.
Submit your ps2_partI.pdf
file using these steps:
-
If you still need to create a PDF file, open your
ps2_partI
file on Google Drive, choose File->Download->PDF document, and save the PDF file in yourps2
folder. -
Login to Gradescope by clicking the link in the left-hand navigation bar, and click on the box for CS 112.
-
Click on the name of the assignment (
PS 2: Part I
) in the list of assignments on Gradescope. You should see a pop-up window labeled Submit Assignment. (If you don’t see it, click the Submit or Resubmit button at the bottom of the page.) -
Choose the Submit PDF option, and then click the Select PDF button and find the PDF file that you created. Then click the Upload PDF button.
-
You should see a question outline along with thumbnails of the pages from your uploaded PDF. For each question in the outline:
- Click the title of the question.
- Click the page(s) on which your work for that question can be found.
As you do so, click on the magnifying glass icon for each page and doublecheck that the pages that you see contain the work that you want us to grade.
-
Once you have assigned pages to all of the questions in the question outline, click the Submit button in the lower-right corner of the window. You should see a box saying that your submission was successful.
Important
-
It is your responsibility to ensure that the correct version of every file is on Gradescope before the final deadline. We will not accept any file after the submission window for a given assignment has closed, so please check your submissions carefully using the steps outlined above.
-
If you are unable to access Gradescope and there is enough time to do so, wait an hour or two and then try again. If you are unable to submit and it is close to the deadline, email your homework before the deadline to
cs112-staff@cs.bu.edu
Part II
47 points total
Important guidelines
The following guidelines apply to the programming problems (i.e.,
problems in which you submit a .java
file) in this and all
subsequent assignments.
-
Your methods must have the exact names that we have specified, or we won’t be able to test them. Note in particular that the case of the letters matters.
-
If a method takes more than one input, you must keep the inputs in the order that we have specified.
-
If you are asked to write a method that returns a value, make sure that it returns the specified value, rather than printing it.
-
In your work on this and all subsequent problem sets, you may not use any of Java’s built-in collection classes (e.g.,
ArrayList
) unless a problem explicitly states that you may do so. We will be writing and using our own collection classes, and using the built-in classes will keep you from fully learning the key concepts of the course. -
More generally, you may not use any built-in class that we have not covered in lecture.
-
Unless the problem states otherwise, you should limit yourself to
String
methods that we have covered in lecture:length
,equals
,substring
,charAt
, andindexOf
. -
You may freely use code from the class website, assigned readings, and lecture notes (unless specifically directed otherwise), as long as you cite the source in your comments. However, you may never use code from anywhere else (e.g., elsewhere on the web, or code obtained from another person). You should also not share your own code with others. See our collaboration policies for more details.
-
Each of your methods should be preceded by a comment that explains what your method does and what its inputs are. In addition, you should include a comment at the top of the file with your name, email, and a description of the program or class of objects represented by the class definition in that file.
-
More generally, use good programming style. Use appropriate indentation, select descriptive variable names, insert blank lines between logical parts of your program, and add comments as necessary to explain what your code does. See the coding standards for more detail.
-
At a minimum we expect that your submitted code will compile. If your code does not compile during our tests, you will not receive any credit for that specific problem.
Problem 6: Practice with static methods
12 points total; individual-only
In a class named MyMethods
, implement each of the methods described
below.
-
a static method called
printDecreasing
that takes aString
as its parameter and prints decreasing substrings of the original string. For example, the callprintDecreasing("method")
should produce the following output:method metho meth met me m
This method should not return a value. Hint: You may find it helpful to use a
for
loop with a header that does not match one of the usual templates.Note: We strongly encourage you to add a
main
method for testing as we did in the previous problem. -
a static method called
firstAndLast
that takes a stringstr
as its parameter and returns a new string formed by combining the first and last characters ofstr
. If the string has only one character, the method should just return the original string. For example:-
firstAndLast("Boston")
should return the string"Bn"
-
firstAndLast("University")
should return the string"Uy"
-
firstAndLast("a")
should return the string"a"
You may assume that
str
has at least one character. This method should not do any printing. Rather, it should return the appropriate string. Hint: You will need to use conditional execution. -
-
a static method called
lastIndexOf
that takes as its two parameters a stringstr
and a characterch
and returns the index of the last occurrence ofch
instr
. Ifch
does not appear instr
at all, the method should return -1. For example:-
lastIndexOf("Boston", 'o')
should return4
-
lastIndexOf("banana", 'a')
should return 5 -
lastIndexOf("banana", 'b')
should return 0 -
lastIndexOf("banana", 'x')
should return -1
This method should not do any printing; rather, it should return the appropriate integer.
Important: You may not use the built-in
lastIndexOf
methods!Hints:
-
One way to solve this problem is to use a
for
loop that examines at one character at time, starting at the end of the string and working backwards towards the beginning of the string. As soon as you find an occurrence of the character you must somehow signal for the loop to stop (think through the conditional expression that controls the loop) or you can use the break statement. -
You will need to use conditional execution.
-
-
a static method called
repeat
that takes as its two parameters a stringstr
and an integern
and returns a new string consisting ofn
copies ofstr
. You may assume thatn
is positive. For example:-
repeat("Java", 3)
should return the string"JavaJavaJava"
-
repeat("oh!", 7)
should return the string"oh!oh!oh!oh!oh!oh!oh!"
This method should not do any printing; rather, it should construct and return the appropriate string.
Hints:
-
You will need to gradually build up the return value using string concatenation. To do so, we recommend that you use a variable for your return value and that you give it the empty string as its initial value:
String result = "";
This will allow you to gradually add to the result by using statements that look like the following:
result = result + expr;
where
expr
is replaced by an appropriate expression. -
You will need to use a
for
loop as part of your implementation of this method.
-
Additional testing
Once you have completed all of these methods, you should use the
following test program to test them:
TestMyMethods.java
Problem 7: Palindrome
20 points total; individual-only
For this problem, we will continue to explore using Java to do input and output, and in particular focus on using Strings. String reference is a simple reference on Strings. Googling “Java String library” or “Java Character library” will produce many references with explanations about these libraries For full details, the canonical reference on these libraries is the Oracle online Java page, which contains every detail you need to know: String, Character.
Begin by downloading StringTest.java. Execute the program as is; you will see that it inputs a sequence of strings and simply prints them out between double quotes. The program will continue to do this until you enter “quit” or if force quit by entering Control-d [hold down the Control key and hit the letter “d”] if you are running your program in a control terminal.
Using the program StringTest.java
as a guide, write a new program
PalindromeTest.java
. The file should contain the two methods as
specified below.
-
Write the method
isPalindrome
which should have the following signature:public static boolean isPalindrome( String s ) { boolean isPal = false; // assume that it is not // code to determine if the string s is a palindrome // If the default (as above) assumes the string is not a palindrome, // the logic here should determine if it is and reassign the return // variable isPal appropriately, or vice verse. return( isPal ); }
Encode the logic of the method:
-
Convert the string
s
to all lower case. -
Remove any character from the string which is neither a letter nor a digit. Hint: use replace(....) to replace any non-letter non-digit by the empty String “”.
-
Check if the string
s
is a palindrome by checking to see if each letter is the same as the letter in its “mirror image” position; for example “Taco Cat” and “Toot!” are palindromes:but honor is not.
-
NOTE: There are multiple ways that you can solve this problem, but you are to follow the steps outlined. For example, you may NOT form the solution to the problem by converting the String to a char array first OR reverse the String and then compare if they are equal.
- Write the method
inputStringPalindrome
which should have the following signature:public static int[] inputStringPalindrome()
This method should prompt the user to enter a string, invoke the
isPalindrome
method you have written and output whether or
not the string entered is or is not a palindrome.
The method should run continuously until the user signals
that
they are done. When end of input is signalled, the method
should simply output a goodbye message and return an array. The
retunred array should contain data on how many times the
isPalindrome
method was called,
and how many of the strings input were palindromes. Specifically, the
first element of the array should reflect how many times the method was
called, and the second element of the array should reflect how many
of the input strings, if any, were palindromes.
Test your code on at least the following palindromes:
A man, a plan, a canal, Panama! Go hang a salami, I'm a lasagna hog! Campus Motto: Bottoms up, Mac! 7/1/17 // A palindrome date! Are we not pure "No sir!" Panama's moody Noriega brags. It is garbage! Irony dooms a man; a prisoner up to new era.
Note that the last quote may cause a problem because there are various kinds of “smart quotes” which are different from the simple ASCII double quotes; if all the others work and this one doesn’t, don’t worry about it!
Also test your code on a non-palindrome example – such as the word “palindrome” itself, or this sentence!
Important guidelines:
-
You may not use recursion to solve this problem.
-
Your methods must follow the exact signature stated above.
-
Follow the
StringTest.java
example as a guide for yourinputStringPalindrome
method as this is how we will test it. Your method should continue to prompt for and accept user input until the wordquit
is entered.
Problem 8: Array-processing methods
15 points total individual-only
In a class named ArrayMethods
, implement each of the methods
described below.
Important guidelines:
-
Your methods must have the exact headers that we have specified, or we won’t be able to test them. Note in particular that the case of the letters matters.
-
If you are asked to write a method that returns a value, make sure that it returns the specified value, rather than printing it.
-
You should not use any Java classes that we have not covered in the lecture notes.
-
Each of your methods should be preceded by a comment that explains what your methods does and what its inputs are. You should also include a comment at the top of the file, similar to the one that we included in
Methods.java
. -
More generally, use good programming style. Use appropriate indentation, select descriptive variable names, insert blank lines between logical parts of your program, and add comments as necessary to explain what your code does. See the coding conventions for more detail.
-
Include the following class declaration at the beginning of your class:
public static final String[] DAYS = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday, "Friday", "Saturday"};
This array, declared at the class level, is a static final array of strings. Each element of this array reprsents a day of the week. Declaring this array static means it has class level scope and can be accessed by any method written in this class. We will only be using it in one of the methods. Declaring this array to be final means it is read only and cannot be modified.
By convention, variables declared to be constant variables (i.e. final) are typically always in upper case. This way when you are looking through code and see a variable in all upper case, you should be able to assume that the variable is read only.
-
Write a method with the header
public static void swapAdjacent(int[] values)
that takes a reference to an array of integers
values
and swaps adjacent pairs of elements:values[0]
withvalues[1]
,values[2]
withvalues[3]
, etc.For example, after implementing this method and compiling your
ArrayMethods
class, you should see the following when you test the method programmatically:int[] a1 = {0, 2, 4, 6, 8, 10}; ArrayMethods.swapAdjacent(a1); System.out.println( Arrays.toString(a1) );
should output:
[2, 0, 6, 4, 10, 8]
In an odd-length array, the last element should not be moved:
int[] a2 = {1, 2, 3, 4, 5, 6, 7}; ArrayMethods.swapAdjacent(a2); System.out.println( Arrays.toString(a2) );
should output:
[2, 1, 4, 3, 6, 5, 7]
Special case: If the parameter is
null
, the method should throw anIllegalArgumentException
. -
Write a method with the header
public static int[] copyReplace(int[] values, int oldVal, int newVal)
that takes a reference to an array of integers
values
and two integersoldVal
andnewVal
, and that creates and returns a new array that is a copy of the original array, but in which all occurrences of the valueoldVal
are replaced with the valuenewVal
.Important:
-
You may not use any of the built-in methods for copying an array.
-
Your method must not modify the original array.
Examples:
int[] a1 = {2, 5, 4, 2, 7, 4, 2}; int[] a2 = ArrayMethods.copyReplace(a1, 4, 0); System.out.println( Arrays.toString(a2) );
should output:
[2, 5, 0, 2, 7, 0, 2]
and,
int[] a3 = ArrayMethods.copyReplace(a1, 2, -1); System.out.println( Arrays.toString(a3) );
should output:
[-1, 5, 4, -1, 7, 4, -1]
while,
System.out.println( Arrays.toString(a1) );
should output:
[2, 5, 4, 2, 7, 4, 2]
Special case: If the parameter is
null
, the method should throw anIllegalArgumentException
. -
-
Write a method with the header
public static int maxSorted(int[] values)
that takes a reference to an array of integers and returns the length of the longest sorted sequence of integers in the array. For example:
int[] a1 = {3, 8, 6, 14, -3, 0, 14, 207, 98, 12}; System.out.println( ArrayMethods.maxSorted(a1) );
should output:
4
The above call should return
4
, because the longest sorted sequence in the array has four values in it (the sequence-3, 0, 14, 207
). Note that the sorted sequence could contain duplicates. For example:int[] a2 = {17, 42, 3, 5, 5, 5, 8, 4, 6, 1, 19}; System.out.println( ArrayMethods.maxSorted(a2) );
should output:
5
This call should return
5
for the length of the sequence3, 5, 5, 5, 8
.Special cases:
-
If the parameter is
null
, the method should throw anIllegalArgumentException
. -
Your method should return
0
if passed an empty array (i.e., an array of length 0). -
Your method should return
1
if passed an array with one element or an array in which all of the elements are in decreasing order. It should be possible to get a return value of 1 for these cases without needing to explicitly check for them.
-
-
Write a method with the header
public static int getIndexOfDay(String day)
that takes a reference to a string and returns the index of that string in the class array
DAYS
. For example:System.out.println( ArrayMethods.getIndexOfDay("Monday") );
should output:
1
The above call should return
1
, because the string “Monday” is found at position1
of the array.Special cases:
-
If the parameter is
null
, or the string is not found in the array the method should return-1
. -
The method should work correctly regardless of case. The Strings
Monday
andmonday
should produce the same output.
-
-
Write a method with the header
public static int[] reverseInterchange( int[] arr1, int [] arr2 )
that takes references to two
integer
arrays and returns a referene to a thirdinteger
array. Your method should copy the elements from the two arrays passed to the array that will be returned, but interchanged from a forward and reverse direction.int a1[] = {1,2,3,4,5,6}; int a2[] = {10,11,12,13}; System.out.println( Arrays.toString( ArrayMethods.reverseInterchange(a1, a2) ) );
should output:
[1,13,2,12,3,11,4,10]
Special cases:
-
If either argument (i.e. parameter) is
null
, the method should throw anIllegalArgumentException
. -
If the length of the two arrays passed to the method are different, only interchange as many elements as are in the smallest of the two arrays. See above example.
-
Submitting your work for Part II
Note: There are separate instructions at the end of Part I that you should use when submitting your work for that part of the assignment.
Submission checklist for Part II
-
You have read the Java coding conventions and followed all guidelines regarding format, layout, spaces, blank lines, and comments.
-
You have ensured that your methods have the names, parameters, and return types specified in the assignment.
-
You have verified that your code satisfies all of the tests that we have provided, and you have conducted whatever other tests are needed to ensure that your code works correctly. If we are unable to compile your work for a given problem, you will not receive any credit for that problem.
You should submit only the following files:
MyMethods.java
PalindromeTest.java
ArrayMethods.java
Make sure that you do not try to submit a .class
file or a file
with a ~
character at the end of its name.
Here are the steps:
-
Login to Gradescope as needed by clicking the link in the left-hand navigation bar, and then click on the box for CS 112.
-
Click on the name of the assignment (
PS 2: Part II
) in the list of assignments. You should see a pop-up window with a box labeled DRAG & DROP. (If you don’t see it, click the Submit or Resubmit button at the bottom of the page.) -
Add your files to the box labeled DRAG & DROP. You can either drag and drop the files from their folder into the box, or you can click on the box itself and browse for the files.
-
Click the Upload button.
-
You should see a box saying that your submission was successful. Click the
(x)
button to close that box. -
The Autograder will perform some tests on your files. Once it is done, check the results to ensure that the tests were passed. If one or more of the tests did not pass, the name of that test will be in red, and there should be a message describing the failure. Based on those messages, make any necessary changes. Feel free to ask a staff member for help.
Note: You will not see a complete Autograder score when you submit. That is because additional tests for at least some of the problems will be run later, after the final deadline for the submission has passed. For such problems, it is important to realize that passing all of the initial tests does not necessarily mean that you will ultimately get full credit on the problem. You should always run your own tests to convince yourself that the logic of your solutions is correct.
-
If needed, use the Resubmit button at the bottom of the page to resubmit your work. Important: Every time that you make a submission, you should submit all of the files for that Gradescope assignment, even if some of them have not changed since your last submission.
-
Near the top of the page, click on the box labeled Code. Then click on the name of each file to view its contents. Check to make sure that the files contain the code that you want us to grade.
Important
-
It is your responsibility to ensure that the correct version of every file is on Gradescope before the final deadline. We will not accept any file after the submission window for a given assignment has closed, so please check your submissions carefully using the steps outlined above.
-
If you are unable to access Gradescope and there is enough time to do so, wait an hour or two and then try again. If you are unable to submit and it is close to the deadline, email your homework before the deadline to
cs112-staff@cs.bu.edu