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
-
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: 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:
- Which of these variables could be printed by the first println statement?
- Which of them could be printed by the second println statement?
- Which of them could be printed by the third println statement?
- Which of them could be printed by the fourth println statement?
- Which of them could be printed by the fifth println statement?
- 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) |
|
|
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
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.
-
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 3: 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 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 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 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]); } }
-
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 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 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 offoo()
—just before its first statement is executed. -
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 offoo()
—just before it returns. -
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 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 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 |
|
|
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.
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
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
, 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: 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:
-
The
'e'
from"heart
” is displayed without modification because it appears in the mystery word ("depth"
) and its position in"heart"
(position 1) is the correct one because it matches the position of the'e'
in"depth"
. -
The
'h'
and't'
from"heart"
are displayed surrounded by square brackets because these characters appear in"depth"
, but their positions in"heart"
are not the correct ones. -
The
a
andr
from"heart"
are each replaced with an underscore character (_
) because'a'
and'r'
do not appear anywhere in"depth"
.
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
-
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. -
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. -
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.
-
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. -
Read over the starter code in
Wordle.java
.Note: The other two files that we’ve given you (
WordList.java
andwords.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:
-
All of your method headers should begin with the keyword
public
. -
You do not need to handle bad inputs – inputs with a value that doesn’t correspond to the description of the inputs provided in the problem.
Here are the methods that you should add to Wordle.java
:
-
a static method called
includes
that takes two parameters: an arbitraryString
objects
followed by a singlechar
c
. The method should return the boolean literaltrue
ifc
is found somewhere ins
, and it should return the boolean literalfalse
otherwise. For example:-
includes("hello", 'e')
should returntrue
, because'e'
is found in position1
of"hello"
-
includes("hello", 'l')
should returntrue
, because'l'
is found in positions2
and3
of"hello"
-
includes("goodbye", 'x')
should returnfalse
, 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:-
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. -
The name
Tester.java
should appear in the Explorer pane in VS Code, along with the other files in yourps2
folder. Click on the name of the file to open an editor window it. -
In the provided
main
method, we’ve included the following sample test call for theincludes
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
). -
Right click on
Tester.java
and choose Run to compile and run the program. If VS Code reports problems inTester.java
, that probably means that there is an issue in your implementation of theincludes
method. In particular, make sure that you have the correct header. Make whatever changes are needed to your methods to getTest7.java
to compile and run. -
Check to make sure that the provided test produces the correct result.
-
Add some additional test calls to ensure that your implementation of
includes
works correctly in all cases.
-
-
a static method called
isAlpha
that takes an arbitraryString
objects
as its only parameter and returnstrue
if all of the characters ins
are letters of the alphabet, and returnsfalse
otherwise. For example:-
isAlpha("Hello")
should returntrue
because all of the characters in"Hello"
are letters of the alphabet -
isAlpha("Goodbye!")
should returnfalse
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 theCharacter
class. The callCharacter.isAlphabetic(c)
will returntrue
ifc
is a letter of the alphabet andfalse
otherwise. -
You will need to process the string
s
one character at a time. The easiest way to do that is using afor
loop. For example, here is a loop that prints the characters in the strings
“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. -
-
a static method called
numOccur
that takes two parameters: a singlechar
c
followed by an arbitraryString
objects
. The method should count and return the number of times thatc
occurs ins
. 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. -
-
a static method called
numInSamePosn
that takes three parameters: a singlechar
c
followed by twoString
objectss1
ands2
that you may assume have the same length. The method should count and return the number of times thatc
occurs in the same position in boths1
ands2
. 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:
- be exactly 5 characters long
- contain only letters of the alphabet.
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:
-
isValidGuess("hello")
should returntrue
-
isValidGuess("hi")
should print the first error message above and returnfalse
-
isValidGuess("what?")
should print the second error message above and returnfalse
-
isValidGuess("abcde")
should returntrue
. (Note: In the actual online version of Wordle,"abcde"
would not be considered valid because it is not one of the words in Wordle’s word list. In our version of the game, any five-letter string is considered a valid guess, regardless of whether it is an English word.)
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:
-
provide feedback to the user about how
guess
compares tomystery
by printing the appropriate sequence of characters (see below) -
return
true
ifguess
is equal tomystery
andfalse
otherwise.
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:
-
If the character at a given position of
guess
matches the character at the corresponding position inmystery
, you should print the character itself without modification. -
If the character at a given position of
guess
does not match the character at the corresponding position ofmystery
but it is needed elsewhere to get the word specified bymystery
, you should print it surrounded by square brackets (e.g., `”[a]”). See below for more detail about what it means for a character to be needed elsewhere! -
If the character is not needed elsewhere to get
mystery
, you should print an underscore 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:
-
Begin by printing two spaces so that the feedback string is properly indented.
-
Print a single space after whatever it prints for each character.
-
Print a newline at the end of the entire feedback string. An easy way to do this is to use an “empty”
println
statement:System.out.println();
-
Return the appropriate boolean value as described above.
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:
-
processGuess("stain", "edict")
should print:_ [t] _ [i] _
and return
false
. -
processGuess("light", "edict")
should print:_ [i] _ _ t
and return
false
. -
processGuess("merit", "edict")
should print:_ [e] _ [i] t
and return
false
. -
processGuess("edict", "edict")
should print:e d i c t
and return
true
.
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:
-
creates a
Scanner
that will be used to read the user’s inputs -
calls the separate method
printWelcome
to print a welcome message for the user -
creates an object of type
WordList
that will represent the collection of possible 5-letter words that the user could be asked to guess -
makes a call to a method called
getRandomWord
in theWordList
object to choose the mystery word, and assigns it to a variable calledmystery
.
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:
-
If the user successfully guessed the mystery word, you should print the following:
Congrats! You guessed it!
-
If the user made 6 guesses without guessing the mystery word, you should print a message with the following format:
Sorry! Better luck next time! The word was _____.
where you replace the blank line with the mystery word.
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:
-
As needed, open the folder containing your code by using the File->Open Folder or File->Open menu option in VS Code.
-
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.
-
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.
-
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:
-
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 ofprocessGuess
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 ofprocessGuess
should print the following instead:_ o _ _ l
- mystery word is
-
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 ofprocessGuess
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! - mystery word is
-
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 callprocessGuess("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. - mystery word is
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:
-
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 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.
-
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 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.
-
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.
-
-
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