CS 112
Spring 2024

Problem Set 2

due by 11:59 p.m. on Tuesday, February 6, 2024

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

45 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

  1. If you haven’t already created a folder named cs112 for your work in this course, follow these instructions to do so.

  2. Then create a subfolder called ps2 within your cs112 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:

  1. Access the template that we have created by clicking on this link and signing into your Google account as needed.

  2. When asked, click on the Make a copy button, which will save a copy of the template file to your Google Drive.

  3. Select File->Rename, and change the name of the file to ps2_partI.

  4. Add your work for the problems from Part I to this file.

  5. 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: Variable scope

9 points total; individual-only

See the section above for guidelines that you should follow to create the file containing your answers to Part I.

Consider the following program, which includes a number of incomplete println statements:

public class ScopeThisOut {
    public static void doSomething(int a) {
        int b = 5;
        System.out.println(________);            // first println

        for (int i = 1; i <= 5; i++) {
            System.out.println(________);        // second println
            int c = 2;
            for (int j = 0; j < 3; j++) {
                System.out.println(________);    // third println
                int d = 4;
            }
        }

        System.out.println(________);            // fourth println
    }

    public static void main(String[] args) {
        int x = 5;

        System.out.println(________);            // fifth println

        int y = 2;
        doSomething(x);

        System.out.println(________);            // sixth println
    }
}

The program includes a number of int variables: a, b, c, d, i, j, x and y. Given the rules that we have learned about variable scope:

  1. Which of these variables could be printed by the first println statement?
  2. Which of them could be printed by the second println statement?
  3. Which of them could be printed by the third println statement?
  4. Which of them could be printed by the fourth println statement?
  5. Which of them could be printed by the fifth println statement?
  6. Which of them could be printed by the sixth println statement?

Note that we are only focusing on the variables of type int, so you can ignore the args parameter of the main method.

Problem 2: String objects and their methods

6 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)

s1 = 'Boston'
s2 = "University"

String s1 = "Boston";
String s2 = "University";

concatenation

s1 + s2

s1 + s2

finding the number of characters

len(s1)

s1.length()

indexing
(note: Java does not have negative indices)

s1[0]
s2[-1]

s1.charAt(0)
s2.charAt(s2.length()-1)
(see the notes below the table for a key fact about this method)

slicing

s1[1:4]
s2[3: ]
s1[ :5]

s1.substring(1, 4)
s2.substring(3)
s1.substring(0, 5)

converting all letters to uppercase

s1.upper()

s1.toUpperCase()

converting all letters to lowercase

s2.lower()

s2.toLowerCase()

determining if a substring is in a string

s2 in s1
'sit' in s2

s1.contains(s2)
s2.contains("sit")

finding the index of the first occurrence of a character or substring

s1.find("o")
s2.find('ver')

s1.indexOf('o')
s2.indexOf("ver")

testing if two strings are equivalent

s1 == s2
s1 == 'Boston'

s1.equals(s2)
s1.equals("Boston")

Notes:

Given the information above, here are the tasks you should perform:

  1. (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
    
  2. (6 points) Assume that the following statements have already been executed:

    String str1 = "Write a string";
    String str2 = "about spring";
    

    For each of the following values, construct an expression involving operations on str1 and/or str2 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.

    1. Construct an expression involving str1 and/or str2 that produces the following value:

      "about a string"
      

      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.

    2. Construct an expression involving str1 and/or str2 that produces the following value:

      "bring"
      
    3. Construct an expression involving str1 and/or str2 that produces the following value:

      "write SPRING"
      

      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)
      
    4. Construct an expression involving str1 and/or str2 that produces the following value:

      'e'
      

      Note that the single quotes mean that you must produce a char, not a String. See the notes under the table above that discuss the char type.

    5. Construct an expression involving str1 and/or str2 that produces the following value:

      "og"
      
    6. Construct an expression involving str1 and/or str2 that produces the following value:

      13
      

      Hint: Use the indexOf method to find a character in str1 or str2.

    7. Construct an expression involving str1 and/or str2 that produces the following value:

      "Wrote a strong"
      

      Use the first replace method in the String class; consult the API of the String class to figure out how to use it.

Problem 3: Understanding code that uses an array

8 points total; individual-only

  1. (4 points) Consider the following static method, which operates on an array of integers:

    public static void mystery(int[] arr) {
        for (int i = 0; i < arr.length - 2; i++) {
            int val1 = arr[i + 1];
            int val2 = arr[i + 2];
            arr[i] = val1 + val2;
    
            // What values do the variables have here,
            // for each value of the loop variable `i`?
        }
    }
    

    Consider the following code fragment, which calls this method:

    int[] values = {1, 3, 5, 7, 9, 11, 13};
    mystery(values);
    

    In section 3-1 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 variable i, 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 of i. 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. (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 the Arrays.toString() method.)

Problem 4: 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?

        int[] c = {1, 2, 3, 4};
        for (int i = 0; i < c.length; i++) {
             a[i] = c[i];
        }
        b = c;

        // part 3: what do things look like when we get here?
    }

    public static void main(String[] args) {
        int[] a = {3, 5, 7, 9};
        int[] b = a;
        int[] c = new int[a.length];

        // part 1: what do things look like when we get here?

        foo(c, b);

        // part 4: what do things look like when we get here?

        System.out.println(a[2] + " " + b[2] + " " + c[2]);
    }
}
  1. In section 4-1 of ps2_partI (see above), we have given you the beginnings of a memory diagram. On the stack, we have included a stack frame for the main method. On the heap, we have included the array to which the variable a refers.

    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.

  2. In section 4-2 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 of foo()—just before its first statement is executed.

  3. In section 4-3 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 of foo()—just before it returns.

  4. In section 4-4 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 to foo() has returned—just before the print statement executes in main().

    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 5: 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

len(grid)

grid.length

determining the number of elements in row r

len(grid[r])

grid[r].length

determining the number of columns in a rectangular grid/matrix (in which all rows have the same length)

len(grid[0])

grid[0].length

accessing the element at row r, column c

grid[r][c]

grid[r][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} };
  1. (2 points) Write an assignment statement that replaces the value of 7 in the above array with a value of 14.

  2. (3 points) Write a code fragment that prints the values in the leftmost 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:

    1
    5
    9
    13
    

    Make your code general enough to work on any two-dimensional array named twoD that has at least one value in each row.

  3. (5 points) Write a code fragment that prints the values in the anti-diagonal of the array to which twoD refers – i.e., the values along a diagonal line from the lower-left corner to the upper-right corner. Print each value on its own line. For the array above, the following values would be printed:

    13
    10
    7
    4
    

    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.

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:

  1. 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 your ps2 folder.

  2. Login to Gradescope by clicking the link in the left-hand navigation bar, and click on the box for CS 112.

  3. 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.)

  4. 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.

  5. 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.

  6. 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

50 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, and indexOf.

  • 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, part I

16 points total; pair-optional

This is the only problem of the assignment that you may complete with a partner. See the rules for working with a partner on pair-optional problems for details about how this type of collaboration must be structured.

This problem asks you to write a series of static methods.

Getting started

  1. If you haven’t already done so, create a folder named ps2 for your work on this assignment.

  2. Download the following file: Methods6.java

    Make sure to put the file in your ps2 folder. If your browser doesn’t allow you to specify where the file should be saved, try right-clicking on the link above and choosing Save as... or Save link as..., which should produce a dialog box that allows you to choose the correct folder for the file.

  3. In VS Code, select the File->Open Folder or File->Open menu option, and use the resulting dialog box to find and open the folder that you created for this assignment. (Note: You must open the folder; it is not sufficient to simply open the file.)

    The name of the folder should appear in the Explorer pane on the left-hand side of the VS Code window, along with the name of the Methods6.java file that you downloaded in step 2.

  4. Click on the name Methods6.java, which will open an editor window for that file. Add the methods described below to the class in that file.

Make sure that you follow the important guidelines given above at the start of Part II. In addition:

Here are the methods you should implement:

  1. a static method called printVertical that takes a String as its parameter and prints the characters of the string vertically — with one character per line. For example, a call of printVertical("method") should produce the following output:

    m
    e
    t
    h
    o
    d
    

    We have given you this example method in the starter file.

    Testing your methods
    To help you test your methods, we’ve provided a main method in Methods6.java that you can use to make appropriate test calls, and we’ve included a sample test call for printVertical.

    You can see if the test calls produce the correct output by running the program. One way to do so in VS Code is to right-click on the name Methods6.java in the Explorer Pane and choose Run.

  2. a static method called printEveryOther that takes a String as its parameter and prints every other character of the string – i.e., the first character, the third character, etc. For example, a call of printEveryOther("method") should produce the following output:

    mto
    

    This method should not return a value.

    Hint: Use printVertical as a model.

    To test your method, add one or more test calls to the main method, and run the program to see if you get the expected results.

  3. a static method called longerLen that takes two String objects as parameters and returns the length of the longer of the two strings. If the two strings have the same length, you should return that length. For example:

    • a call of longerLen("bye", "hello") should return 5, because 5 is the length of "hello", which is the longer of the two strings.

    • a call of longerLen("goodbye", "hi") should return 7, because 7 is the length of "goodbye", which is the longer of the two strings.

    This method should not do any printing; rather, it should determine the longer length and return it.

    Hint: Because this method returns a value and doesn’t print anything, you’ll need to perform the necessary printing yourself when you test it. For example, you could add these lines to the main method:

    int len = longerLen("bye", "hello");
    System.out.println("the longer length is: " + len);
    
  4. a static method called secondIndex that takes as its two parameters a string s and a character c and returns the index of the second occurrence of c in s (if any). If s does not have at least two occurrences of c, the method should return -1.

    For example:

    • a call of secondIndex("banana", 'a') should return 3, because the second occurrence of 'a' in "banana" occurs at position 3 in the string

    • a call of secondIndex("banana", 'n') should return 4, because the second occurrence of 'n' in "banana" occurs at position 4 in the string.

    • a call of secondIndex("banana", 'b') should return -1, because there is only one 'b' in "banana".

    • a call of secondIndex("banana", 'x') should return -1, because there is no 'x' in "banana".

    This method should not do any printing; rather, it should return the appropriate integer.

Additional testing
Once you have completed all of these methods, you should run a separate test program that we’ve created. This is an important step as it will help to identify any issues in your methods that might prevent us from grading them.

Here’s how to use the test program:

  1. Download the following file: Test6.java

    Put it in your ps2 folder with your Methods6.java file.

  2. As needed, open your ps2 folder using the File->Open Folder or File->Open menu option in VS Code. The name of the folder should appear in the Explorer pane on the left-hand side of the VS Code window, along with the names of both the Methods6.java and Test6.java files.

  3. Right click on Test6.java and choose Run to compile and run the program. If the IDE reports errors in Test6.java, that probably means that at least one of your methods does not have the correct header — i.e., either the name, the return type, or the parameters are incorrect. Make whatever changes are needed to your methods to get Test6.java to compile and run.

  4. Once Test6.java does compile and run, you should check the results that it produces; the correct results are given in the descriptions of the methods above.

  5. Feel free to add additional test cases to the ones that we’ve provided.

Problem 7: Practice with static methods, part II

21 points total; individual-only

The guidelines at the start of Part II and at the beginning of Problem 6 also apply here.

Getting started

  1. As needed, open your ps2 folder using the File->Open Folder or File->Open menu option in VS Code.

  2. Select File->New File, which will open up an empty editor window.

  3. Select File->Save, and give the new file the name Methods7.java.

  4. In the new file, create a class called Methods7. In that class, implement each of the methods described below.

Here are the methods you should implement:

  1. a static method called printDiag that takes a string as its only parameter and prints each character of the string on a separate line, with enough spaces before each character so that the string is printed “diagonally”. For example, a call of printDiag("method") should produce the following output:

    m
     e
      t
       h
        o
         d
    

    where the first character is preceded by 0 spaces, the second character is preceded by 1 space, etc.

    This method should not return a value.

    Hint: You may find it helpful to use a nested for loop.

    Note: We strongly encourage you to add a main method for testing as we did in the previous problem.

  2. a static method called lastN that takes as its two parameters a string s and an integer n, and that returns a string consisting of the last n characters of s. For example:

    • a call of lastN("programming", 5) should return the string "mming"

    • a call of lastN("programming", 1) should return the string "g".

    You may assume that the value of n is positive. This method should not do any printing. Rather, it should extract the appropriate string and return it.

    Special case: If the value of n is greater than the length of the string, the method should return the entire string. For example, a call of lastN("programming", 15) should return the string "programming". You should use conditional execution to allow your method to handle this special case.

  3. a static method called remSub that takes two strings as parameters and returns the string produced when you remove the first occurrence of the second string from the first string. For example:

    • a call of remSub("ding-a-ling", "ing") should return the string "d-a-ling"
    • a call of remSub("variable", "var") should return the string "iable".

    This method should not do any printing; rather, it should construct and return the appropriate string.

    Important: You may not use the replaceFirst method of the String class in your solution.

    Special case: If there are no occurrences of the second string in the first string, the method should return the first string. For example, a call of remSub("Boston", "ten") should return the string "Boston".

    Hints:

    • Recall that there is a String method called indexOf that takes a char and returns the index of the first occurrence of that char in a String. There is a similar method with the same name that takes a String as its parameter instead of a char. You should use that method to determine the position of the first occurrence of the second string in the first string. Given that position, you should then be able to construct the string that your method will return. Find this version of the indexOf method in the API of the String class, and use the information provided in the API to construct an appropriate method call.

    • You should use conditional execution to handle the special case described above. Note that the version of the indexOf method mentioned in the previous hint will allow you to determine if you have the special case.

  4. a static method called interleave that takes two strings s1 and s2 as parameters and returns the string formed by “interleaving” the characters in s1 and s2. In other words, it should create a new string by alternating characters from the two strings: the first character from s1, followed by the first character from s2, followed by the second character from s1, followed by the second character from s2, etc.

    For example:

    • a call of interleave("aaaa", "bbbb") should return the string "abababab"
    • a call of interleave("hello", "world") should return the string "hweolrllod"

    If one of the strings is longer than the other, its “extra” characters – the ones with no counterparts in the shorter string – should go immediately after the interleaved characters (if any). The same rule applies if either of the strings is an empty string. For example:

    • a call of interleave("leaving", "NOW") should return the string "lNeOaWving". Note that the extra characters from the first string – the characters in "ving" – are put after the interleaved characters.
    • a call of interleave("", "hello") should return the string "hello"

    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 add one or more characters to the result by using statements that look like the following:

          result = result + expr;
      

      where expr is replaced by whatever expression is needed to obtain the necessary characters.

    • 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: Test7.java

Follow a similar procedure to the one that you used with the Test6.java file for Problem 6.

Problem 8: A simple interactive program

18 points total; individual-only

Overview
This problem provides additional practice with conditional execution and static methods, and it also gives you a chance to write a simple program with repeated user interactions.

The program will allow the user to compute the shipping charge for a collection of one or items. The shipping charge for each item will be based on the following characteristics:

Rules
Here are the rules for determining the charge for a single item:

Example
Let’s say that the user wants to use one-day shipping to ship three items: a 10-pound toy, a 2-pound book, and a piece of clothing that weighs less than 2 pounds. Using the rules for one-day shipping found above:

Thus, the total cost would be $24.89 + $5.19 + $4.99 = $35.07.

(Note: For the sake of greater precision, you will actually perform most of the computations in cents – e.g., 499 instead of 4.99, and 99 instead of 0.99. Then, at the end of the program, you will convert the total cost to dollars. See below for more detail.)

Sample runs
Your final program should match the behavior of the sample runs available here. Note that these sample runs are not comprehensive, and you should make sure to test other cases as well.

Getting started

  1. Download the following file: TerrierShipping.java
    Make sure to put it in your ps2 folder.

  2. As needed, open your ps2 folder using the File->Open Folder or File->Open menu option in VS Code. The name of the folder should appear in the Explorer pane on the left-hand side of the VS Code window, along with the name of the TerrierShipping.java file that you downloaded in step 1.

  3. Click on the name TerrierShipping.java, which will open an editor window for that file. You will see some starter code that we’ve provided. In particular, we’ve given you the beginnings of the main method, along with static methods for getting the type of shipping and the type of an item from the user.

Your tasks

  1. Start by reading over the starter code that we’ve given you. Make sure that you understand it.

  2. Complete the assignment statement in the main method for the variable weight so that it assigns an integer value obtained from the user. At the moment, the statement looks like this:

    int weight = 0;
    

    You should replace the 0 with the appropriate method call.

    Important: You must use the Scanner object created at the start of the main method, and you may not create an additional Scanner object.

  3. Add the code needed to compute the charge for a single item, based on the inputs provided by the user (which you may assume are all valid) and the rules found above. In particular, you must:

    1. Add at least three additional static helper methods, each of which handles the computation of one type of shipping charge. These new methods should go between the getItemType and main methods that we have given you.

      There is more than one possible way to divide up the work among these helper methods. For example, you could have:

      • one method for each type of shipping (one-day, two-day, and standard)

                    or

      • one method for each type of item (book, clothing, electronics, and toy).

      See below for some important requirements that your methods must satisfy.

    2. Add code to main that uses conditional execution to call the appropriate helper method and assign its return value to the variable itemCharge.

    Important requirements
    Each of your static helper methods must:

    • take one or more parameters that provide the necessary information about a single item

    • compute and return the appropriate charge for that item in cents. For example, instead of using a cost of 4.99 dollars, your method should use 499 cents. Keeping the charges in cents until the end of the program will prevent the loss of precision that can result when floating-point numbers (i.e., doubles) are added together.

    The names of the methods are up to you, but you should pick names that describe what the methods are supposed to do.

  4. Complete the line of code provided near the end of main so that it will convert the total charge from cents to dollars. At the moment, the statement looks like this:

    double totalDollars = 0.0;
    

    You should replace the 0.0 with the appropriate expression. Make sure that your computation is as precise as possible.

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:

Make sure that you do not try to submit a .class file or a file with a ~ character at the end of its name.

Pair-optional problem

If you chose to work on this pair-optional problem with a partner, only one person from the pair should submit the file, and that person should add the other person as a group member following step 7 below.

Here are the steps:

  1. Login to Gradescope as needed by clicking the link in the left-hand navigation bar, and then click on the box for CS 112.

  2. 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.)

  3. Add your file to the box labeled DRAG & DROP. You can either drag and drop the file from its folder into the box, or you can click on the box itself and browse for the files.

  4. Click the Upload button.

  5. You should see a box saying that your submission was successful. Click the (x) button to close that box.

  6. The Autograder will perform some tests on your file. 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.

  7. If you worked with a partner and you are the one who is submitting the file:

    • Click on the Add Group Member link that appears below your name above the results of the Autograder.

    • In the pop-up box that appears, click on the Add Member link.

    • Type your partner’s name or choose it from the drop-down menu.

    • Click the Save button.

    • Check to ensure that your partner’s name now appears below your name above the results of the Autograder.

  8. 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.

  9. 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