CS 112
Spring 2022

Old version

This is the CS 112 site as it appeared on May 12, 2022.

Problem Set 2

due by 11:59 p.m. on Tuesday, February 8, 2022

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

50 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 ScopePuzzle {
    public static void myMethod(int e) {
        int i;
        for (i = 0; i < 10; i++) {
            System.out.println(________);        // first println

            int a = 5;
            for (int j = 0; j < 3; j++) {
                int b = 0;
                System.out.println(________);    // second println
            }
            System.out.println(________);        // third println
        }

        int y = 3;
        System.out.println(________);            // fourth println
    }

    public static void main(String[] args) {
        int c = 0;

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

        int d = 1;
        myMethod(c);

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

The program includes a number of int variables: a, b, c, d, e, i, j, 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

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)

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 s1 = "don't string";
    String s2 = "me along!";
    

    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 s1 and/or s2 that produces the following value:

      "string me"
      

      We have given you the answer to this part of the problem in ps1_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 s1 and/or s2 that produces the following value:

      "sing along"
      
    3. Construct an expression involving s1 and/or s2 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)
      
    4. Construct an expression involving s1 and/or s2 that produces the following value:

      "dime"
      
    5. Construct an expression involving s1 and/or s2 that produces the following value:

      'r'
      

      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.

    6. Construct an expression involving s1 and/or s2 that produces the following value:

      "r"
      

      Note that the double quotes mean that you must produce a String, not a char.

    7. Construct an expression involving s1 and/or s2 that produces the following value:

      "dm"
      
    8. Construct an expression involving s1 and/or s2 that produces the following value:

      9
      

      Hint: Use the indexOf method to find a character in s1 or s2.

    9. Construct an expression involving s1 and/or s2 that produces the following value:

      "don'u suring"
      

      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

10 points total; individual-only

  1. (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 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. (2 points) What does the array represented by values look like just before the call to mystery returns?

  3. (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?

        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]);
    }
}
  1. In section 4-1 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 the main method. Outside of the stack, we have included the array to which the variable a refers, and we have used an arrow to represent the reference to that array that is stored in the variable a.

    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 10 in the above array with a value of 30.

  2. (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 in twoD have the same number of elements.

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

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: Implementing a word-guessing game

50 points; 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.

The word game called Wordle has recently become extremely popular online. Articles about the game seem to be everywhere you look. It even made an appearance in a recent skit on Saturday Night Live!

In this problem, you will implement a version of this game that runs in the console.

If you haven’t played Wordle yet, we encourage you to give it a try before you proceed!

Rules of the game
In Wordle, the user is given 6 chances to guess a 5-letter English word. After each guess, the user is given feedback about how close their guess was to the “mystery” word (the word they are trying to guess).

In the online version of Wordle, feedback about a guess is given using colored tiles. Because our version runs in the console, we’ll take an approach that relies purely on text characters for feedback.

For example, imagine that the mystery word is "depth" and that the user guesses "heart". To provide feedback on that guess, the program would print the following:

  [h] e _ _ [t]

Note that:

More details about how to correctly process a guess are provided below.

Here’s an example of what a full run of the program will look like:

Welcome to Wordle!
The mystery word is a 5-letter English word.
You have 6 chances to guess it.

guess 1: stain
  _ [t] _ [i] _
guess 2: light
  _ [i] _ _ t
guess 3: merit
  _ [e] _ [i] t
guess 4: edict
  e d i c t

Congrats! You guessed it!

Getting started

  1. If you haven’t already done so, create a folder named ps2 for your work on this assignment. You can find instructions for doing so here.

  2. Download the following files:

    Make sure to put all three files in your ps2 folder. If your browser doesn’t allow you to specify where a file should be saved, try right-clicking on its 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 names of the files that you downloaded in step 2.

  4. Click on the name Wordle.java, which will open an editor window for that file. You will see that we’ve given you the beginnings of the program.

  5. Read over the starter code in Wordle.java.

    Note: The other two files that we’ve given you (WordList.java and words.txt) will be used to select the random word that the user needs to guess. You should not modify either of those files.

Task 1: Write helper methods that process strings

In this task, you will implement several static methods, each of which processes one of more strings. At least some of these methods will be useful as helper methods in your implementation of Wordle.

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

In addition:

Here are the methods that you should add to Wordle.java:

  1. a static method called includes that takes two parameters: an arbitrary String object s followed by a single char c. The method should return the boolean literal true if c is found somewhere in s, and it should return the boolean literal false otherwise. For example:

    • includes("hello", 'e') should return true, because 'e' is found in position 1 of "hello"

    • includes("hello", 'l') should return true, because 'l' is found in positions 2 and 3 of "hello"

    • includes("goodbye", 'x') should return false, because 'x' is not found in any position of "goodbye".

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

    Hint: One of the built-in String methods that we discussed in lecture and in Problem 2 would be very helpful here!

    Testing your methods
    You should test each method after your write it. Here are the steps you should take:

    1. Download the following file: Tester.java

      Make sure to put it in your ps2 folder. If your browser doesn’t allow you to specify where a 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.

    2. The name Tester.java should appear in the Explorer pane in VS Code, along with the other files in your ps2 folder. Click on the name of the file to open an editor window it.

    3. In the provided main method, we’ve included the following sample test call for the includes method:

      boolean result = Wordle.includes("hello", 'e');
      System.out.println("includes(\"hello\", 'e') returns " + result);
      

      Note: Because we are calling a static method from another class, we need to prepend the class name (Wordle).

    4. Right click on Tester.java and choose Run to compile and run the program. If VS Code reports problems in Tester.java, that probably means that there is an issue in your implementation of the includes method. In particular, make sure that you have the correct header. Make whatever changes are needed to your methods to get Test7.java to compile and run.

    5. Check to make sure that the provided test produces the correct result.

    6. Add some additional test calls to ensure that your implementation of includes works correctly in all cases.

  2. a static method called isAlpha that takes an arbitrary String object s as its only parameter and returns true if all of the characters in s are letters of the alphabet, and returns false otherwise. For example:

    • isAlpha("Hello") should return true because all of the characters in "Hello" are letters of the alphabet

    • isAlpha("Goodbye!") should return false because "Goodbye!" includes a character ('!') that is not a letter of the alphabet.

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

    Hints:

    • To test if a character c is a letter of the alphabet, you may use a built-in method from the Character class. The call Character.isAlphabetic(c) will return true if c is a letter of the alphabet and false otherwise.

    • You will need to process the string s one character at a time. The easiest way to do that is using a for loop. For example, here is a loop that prints the characters in the string s “vertically”, with each character on its own line:

      for (int i = 0; i < s.length(); i++) {
          char c = s.charAt(i);
          System.out.println(c);
      }
      

    Test your method by adding test calls to your Tester class as described above.

  3. a static method called numOccur that takes two parameters: a single char c followed by an arbitrary String object s. The method should count and return the number of times that c occurs in s. For example:

    • numOccur('l', "hello") should return 2, because there are 2 occurrences of 'l' in "hello"

    • numOccur('e', "hello") should return 1, because there is 1 occurrence of 'e' in "hello"

    • numOccur('x', "goodbye") should return 0, because there are no occurrences of 'x' in "goodbye".

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

    Test your method by adding test calls to your Tester class as described above.

  4. a static method called numInSamePosn that takes three parameters: a single char c followed by two String objects s1 and s2 that you may assume have the same length. The method should count and return the number of times that c occurs in the same position in both s1 and s2. For example:

    • numInSamePosn('p', "apple", "maple") should return 1, because there is one position (position 2) at which 'p' occurs in both "apple" and "maple".

    • numInSamePosn('a', "apple", "maple") should return 0, because there are no positions at which 'a' occurs in both "apple" and "maple". Note that the letter 'a' occurs in both strings, but not at the same position.

    • numInSamePosn('a', "java", "mama") should return 2, because there are two position (positions 1 and 3) at which 'a' occurs in both "java" and "mama".

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

    Test your method by adding test calls to your Tester class as described above.

Task 2: Implement the method that tests if a guess is valid

In Wordle.java, we have included an incomplete version of a method called isValidGuess that takes an arbitrary String object guess as its only parameter and returns a boolean value.

The current version of the method always returns true. Rewrite it so that it tests the input string guess and returns true if it is a valid guess for Wordle and false otherwise. If guess is not a valid Wordle guess, you should also print an appropriate error message (see below) before returning.

To be a valid guess in our version of Wordle, a string must:

If guess does not have the correct length, you should print the message:

Your guess must be 5 letters long.

and return false

If guess has the correct length but includes characters that are not letters of the alphabet, you should print the message:

Your guess must only contain letters of the alphabet.

and return false.

If guess is a string of exactly 5 letters, you should return true without printing anything.

For example:

Important: When implementing this method, you should take advantage of one of the helper methods that you implemented in Task 1.

Testing isValidGuess
As before, you can test this method by adding test calls to your Tester class.

Another option is to make calls to a separate static method called readGuess that we have provided in the Wordle class, since readGuess reads a guess from the user and calls isValidGuess to determine if the guess is valid.

readGuess takes two parameters: an integer that specifies the number of the guess that is being read, and a Scanner object that will be used to read the guess. In Tester.java, we have created a Scanner object called console that you can use for this purpose.

Here is one possible user interaction that should result from calling Wordle.readGuess(1, console) in Tester.java and entering the guesses that are underlined below:

guess 1: go
Your guess must be 5 letters long.
guess 1: what?
Your guess must only contain letters of the alphabet.
guess 1: hi!
Your guess must be 5 letters long.
guess 1: apple

Task 3: Implement the method that processes a guess

In Wordle.java, implement a method called processGuess that takes two parameters: a 5-character String object guess representing a guess made by the user followed by a 5-character String object mystery representing the “mystery” word that the user is trying to guess.

The method should process the input string guess and:

Rules for providing feedback
The method should process the string guess one character at a time parameter and print the appropriate output for each character:

For example, the call processGuess("heart", "depth") should print the following

  [h] e _ _ [t] 

and return false. Note that the 'e' in "heart" matches the 'e' in the corresponding position of "depth", the 'h' and the 't' are needed elsewhere in the mystery word, and the 'a' and 'r' are not needed elsewhere.

In addition, the method should:

Initial version of the method
To begin, you should implement a simplified version of processGuess in which a character in the guess is “needed elsewhere” whenever (1) it does not match the character in the corresponding position of the mystery word, and (2) it appears somewhere in the mystery word.

Such a simplified version won’t be fully correct in all cases (see Task 5 below), but it will be good enough for cases in which the user’s guess never includes two or more occurrences of the same character.

Here are some other test cases for this initial version of the method:

Note: You should be able to take advantage of at least one of the helper methods that you implemented in Task 1.

Test your processGuess method by adding test calls to your Tester class.

Task 4: Complete the main method

At the bottom of Wordle.java, we have given you the beginnings of the main method. The code that we have provided:

Add the code needed to obtain and process each of the user’s guesses.

You should use a loop that repeatedly gets a single guess and processes it, continuing until the user guesses the mystery word or until they have made 6 guesses, whichever comes first. Make sure to take advantage of the existing methods – in particular,readGuess and processGuess.

Then, after the loop has ended, you should print an appropriate closing message:

Testing the full program
Once you have completed the main method, you are ready to try playing the game!

When running the program, you must highlight Wordle.java in the list of files before using F5 to run the program. Another option is to right-click on the name of the file in the Explorer pane and choose Run or Run Java.

To get a repeatable mystery word for testing and debugging, you can specify what is known as a seed for the random-number generator that we use to select the random word. Here is one way to do so:

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

  2. If you don’t already have a Terminal pane at the bottom of the VS Code window, use the Terminal->New Terminal menu option to open one.

  3. Enter the following command from the Terminal to compile your code:

    javac Wordle.java
    

    If executing this command produces error messages describing bugs in your code, fix them and try again. Repeat this process until your code compiles without any error messages.

  4. Enter the following command from the Terminal to run your code with a random seed:

    java Wordle seed
    

    where you replace seed with an integer. Here are some seeds and their corresponding mystery words:

     10: pearl
     40: edict
     60: enact
     70: nippy
     90: nutty
    100: depth
    112: towel
    

Task 5: Try to improve processGuess

In this task, you will try to improve your processGuess method so that it will correctly handle cases in which a character appears two or more times in the user’s guess.

Before proceeding, we recommend saving a copy of your current version of Wordle.java in another folder so that you don’t lose your current version of processGuess.

When a character appears more than once in the user’s guess (e.g., if the user guesses "loyal", which has two 'l's), it becomes trickier to determine whether a given instance of the repeated character should be considered as being “needed elsewhere.”

For example, consider the following examples:

  1. processGuess("loyal", "towel")

    • mystery word is "towel"
    • user’s guess is "loyal"

    The first 'l' in "loyal" doesn’t match the corresponding character in "towel" and there is an 'l' in the mystery word. Therefore, the version of processGuess from Task 3 would print the following feedback in this case:

      [l] o _ _ l 

    However, the first 'l' in the user’s guess is not truly needed elsewhere since the guess already has an 'l' in the only position where it is needed – at the very end of the word. Therefore, an improved version of processGuess should print the following instead:

      _ o _ _ l 

  2. processGuess("piper", "nippy")

    • mystery word is "nippy"
    • user’s guess is "piper"

    In this case, there are two 'p's in the mystery word, and the user’s guess also has two 'p's: one in a correct position, and one that is in an incorrect position but is needed elsewhere. Therefore, an improved version of processGuess should print:

      [p] i p _ _ 

    Note: The original version of processGuess would actually handle this case correctly. You should make sure that your improved version continues to do so!

  3. processGuess("nanny", "enact")

    • mystery word is "enact"
    • user’s guess is "nanny"

    In this case, there is only one 'n' in the mystery word but the user’s guess has three 'n's, none of which is in a correct position. Because only one of the three 'n's is needed elsewhere, the call processGuess("nanny", "enact") should print:

      [n] [a] _ _ _ 

    Note that the first 'n' is surrounded by brackets because it is needed elsewhere. But because there is only one 'n' in the mystery word, the other two 'n's are replaced with underscore characters.

Make whatever changes are needed to your processGuess method so that a character that isn’t in the correct position is only printed with brackets around it if it is truly needed elsewhere to form the mystery word. Otherwise, you should print an underscore character instead.

It can be challenging to satisfy all of the possible cases, but taking advantage of the helper methods that you wrote in Task 1 should allow you to at least handle cases like the first two examples above.

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 your Wordle.java file.

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