Old version
This is the CS 112 site as it appeared on December 31, 2020.
Problem Set 1
due by 11:59 p.m. on Sunday, September 20, 2020
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 course instructor or teaching fellow.
Make sure to follow the instructions outlined at the end of the problem set when submitting your assignment.
Using folders
We strongly encourage you to create a separate folder for each
assignment, so that you can more easily keep track of your
work. For example, you could create a folder called ps1
for your
work on this assignment, and put all of the files for PS 1 in
that folder.
Part I Analytics Problems
78 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 entering the code in Eclipse, but we strongly encourage you to answer them on your own and convince yourself of the correctness of your answer. If you choose to also enter the code, you should only do so to verify correctness. These questions are similar to ones that could appear on the midterms and final exam, which you will have to answer without the use of a computer, so it is important to test your own knowledge through these assignments!
Creating the necessary file
Problems in Part I will be completed in a single PDF file. To create it, you should do the following:
-
Open the template that we have created for these problems in Google Docs: ps1_partI
-
Select File->Make a copy..., and save the copy to your Google Drive using the name
ps1_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 on your machine. The resulting PDF file (
ps1_partI.pdf
) is the one that you will submit. See the submission guidelines at the end of the assignment.
Problem 1: Learning to read (Java code)
26 points total; individual-only
-
Suppose that a and b are int values. Simplify the following expressions to a boolean expression involving only a single operator:
(!(a < b) && !(a > b))
( (a < b) == true )
( (a <= b) == false )
(!(a > b) && !(a < a))
( (b < b) || !(a <= b))
-
Which of the following will create an error because of a misuse of types?
int n = 3 + '3';
double x = (3.4 + (int) 2.1) * "3";
String s = "hi" + 5 + 't' + true + "there";
-
What do each of the following print? (Be sure you understand WHY!)
System.out.println(2 + "bc");
System.out.println(2 + 3 + "bc");
System.out.println((2+3) + "bc");
System.out.println("bc" + (2+3));
System.out.println("bc" + 2 + 3);
Problem 2: Java programming basics
10 points total; 5 points each part; individual-only
-
The following program has many syntax errors:
public Class Program1 { /* * This method should take an integer x and return: * 2x when x is odd * the unchanged value of x when x is even */ public int double_if_odd(x) { { if x % 2 = 1: x =* 2; return x } public void main(String[]) scan = Scanner(System.in); print('Enter an integer x: '); integer x = scan.next() print("double_if_odd(x) = ", double_if_odd(x)) } }
Determine and fix all of the problems with this program so that it will compile and do the following when run:
-
Ask the user to enter an integer and store the user’s input in the variable
x
. -
Call the method
double_if_odd
withx
as its input, and print the value returned by that method.double_if_odd
should have the functionality specified in the comment that precedes it.
Here’s what a run of the program should look like if the user enters 5:
Enter an integer x: 5 double_if_odd(x) = 10
Once you are confident that you have fixed all of the problems in the code, put the revised program in your
ps1_partI
file as your answer to this question. (See the guidelines at the start of Part I for how to create this file.) -
-
Assume that the following variable declarations have already been executed:
int f = 15; int g = 2; double h = 2.0; double i = 2; double j = 10.0;
Given the statements above, determine the value of each of the following expressions. Make sure that your answers clearly indicate the type of each value. In particular, floating-point values should have a decimal and strings should be surrounded by double quotes.
-
f + g
-
f + "g"
-
f + h
-
f / g
-
f / h
-
f / i
-
(int)j / f * f
-
(int)(j / f) * f
-
"1" + 1 + 2
-
1 + 1 + "2"
-
Problem 3: Conditional execution
6 points total; 3 points each part; individual-only
Consider the following code fragment:
Scanner scan = new Scanner(System.in); System.out.print("Enter three numbers: "); int a = scan.nextInt(); int b = scan.nextInt(); int c = scan.nextInt(); if (a <= b) { if (b > c || c < 4) { System.out.println("diamond"); } else { System.out.println("ruby"); } System.out.println("pearl"); } else if (b >= c) { if (!(a > b)) { System.out.println("copper"); } else if (b == c && b < 5) { System.out.println("bronze"); } System.out.println("silver"); if (a < c) { System.out.println("gold"); } } else { System.out.println("penny"); if (a == b) { System.out.println("dime"); } else { System.out.println("nickel"); } } System.out.println("done");
-
In section 3-1 of
ps1_partI
(see above), state the output that would result from each of the following sets of inputs:-
3 3 3
-
3 4 5
-
3 5 2
-
5 4 3
-
5 4 7
-
4 4 3
-
-
At least one of the println statements in the above code fragment will not be executed for any set of inputs. Identify the statement(s) and explain why it/they will never be executed.
Problem 4: Static methods
9 points total; individual-only
-
(5 points) Consider the following Java program, which includes two static methods:
public class MethodAdventure { public static int callMe(int a, int b) { b -= 2; a = a - b; System.out.println(a + " " + b); return a; } public static void main(String[] args) { int a = 5; int b = 4; System.out.println(a + " " + b); a = callMe(a, b); System.out.println(a + " " + b); b = 2 * callMe(b, a) + 1; System.out.println(a + " " + b); System.out.println(callMe(a, a)); System.out.println(a + " " + b); } }
In section 4-1 of
ps1_partI
(see above), we have given you tables that you should complete to illustrate the execution of the program.We have started the first and third tables for you. You should:
- complete the first and second tables so that they illustrate how the values of the variables change over time
- complete the last table so that it shows the output of the program (i.e., the values that are printed).
You may not need all of the rows provided in the tables.
-
(4 points) Fill in the blanks below to create a method that takes as parameters two integers
a
andb
, and returns the average of the two values. Make the result as precise as possible, and add the completed method tops1_partI
.public static ______ average(______________________) { ______ avg = ___________________; __________________; }
For example:
- the method call
average(3, 6)
should return4.5
- the method call
average(10, 20)
should return15.0
Note that the body of the method should be exactly two lines: one line that assigns the appropriate expression for the average to to the variable
avg
, and a second line that returns the value ofavg
.Important: In Java, the
/
operator is used for both integer division and floating-point division. In order to get floating-point division — which preserves the digits after the decimal — you need to make sure that at least one of the operands is a floating-point number. If both of the operators are integers, you will get integer division. - the method call
Problem 5: Loops
7 points total; individual-only
-
(2 points) In
ps1_partI
, we have included the following partial code fragment:for (____________; ____________; ____________) { System.out.println("I feel loopy!"); }
Fill in the blanks to create a loop that repeats the message “I feel loopy!” 42 times. Use the approach for obtaining N repetitions that we discussed in lecture.
-
(2 points) Consider the following code fragment:
int i; while (i > 30) { i = 5; System.out.print(i); i++; }
This code is supposed to print the multiples of 5 from 5 to 30 on separate lines, as follows:
5 10 15 20 25 30
However, it currently fails to do so.
We have included the original code fragment in
ps1_partI
. Make whatever changes are needed to obtain the correct output. The corrected version should still use awhile
loop whose condition is based on the value of the variablei
. -
(3 points) Consider the following code fragment:
for (int i = 0; i < 3; i++) { for (int j = 2; j >= 0; j--) { System.out.println(i + " " + j); } System.out.println("--"); }
Modify this fragment to make it produce the following output:
0 0 -- 1 1 1 0 -- 2 2 2 1 2 0 -- 3 3 3 2 3 1 3 0 --
We have included the original code fragment in
ps1_partI
. Make whatever changes are needed to obtain the correct output. The corrected version should still consist of six lines, with one three-linefor
loop nested in anotherfor
loop.
Problem 6: Variable scope
6 points total; 1 point each part; individual-only
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:
- 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 7: String
objects and their methods
14 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 occurence of a character or substring |
|
|
testing if two strings are equivalent |
|
|
Notes:
-
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, these statements:
String s1 = "Boston"; System.out.println( s1.substring(1, 4) );
should display the return value:
"ost"
-
Assume that the following statements have already been executed:
String str1 = "A method"; String str2 = "to my MADNESS";
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
str1
orstr2
that produces the following value:"to my MADNESS a method"`
Note: You will need to explicitly add a space.
-
Construct an expression involving
str1
orstr2
that produces the following value:'h'
Important: 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
str1
orstr2
that produces the following value:"MAD"
-
Construct an expression involving
str1
orstr2
that produces the following value:"YES"
Hint: Part of your expression will need to chain two method calls together. For example:
str2.toLowerCase().substring(9) "ness"
-
Construct an expression involving
str1
orstr2
that produces the following value:"ethos"
-
Construct an expression involving
str1
orstr2
that produces:
the following value:10
Hint: Use the
indexOf
method to find a character instr1
orstr2
. -
Construct an expression involving
str1
orstr2
that produces the following value:"to my BADNESS"
Use the first
replace
method in theString
class; consult the API of theString
class to figure out how to use it.
-
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 ps1_partI.pdf
file using these steps:
-
If you still need to create a PDF file, open your
ps1_partI
file on Google Drive, choose File->Download->PDF document, and save the PDF file on your machine. -
Login to Gradescope by clicking the link in the left-hand navigation bar. (If you don’t have a Gradescope account, you can create one now, but you must use your BU email address and ID number.)
-
Once you are logged in, click on the box for CS 112. (If you don’t see that box, you should email
cs112-staff@cs.bu.edu
so that we can add you to the course’s Gradescope site.) -
Click on the name of the assignment (
PS 1: 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 your instructor.
Part II
22 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.
-
You should not use any Java classes that we have not covered in the lecture notes.
-
Each of your methods should be preceded by a comment that explains what your method does and what its inputs are. In addition, you should include a comment at the top
-
More generally, use good programming style. Use appropriate indentation, select descriptive variable names, insert blank lines between logical parts of your program, and add comments as necessary to explain what your code does. See the coding conventions for more detail.
-
At a very 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.
-
Please make sure to follow the expected naming conventions and submit only the files that are specified at the end of this specification.
Problem 8: A simple interactive program
22 points total; individual-only
This problem provides additional practice with writing static methods, and it also gives you a chance to write a simple program with repeated user interactions. In particular, the program will allow the user to perform a variety of operations on a set of three integers.
Getting started Begin by accessing the following file: SimpleStats.java
It provides a skeleton for your program.
In particular, we’ve given you the beginnings of the main()
method,
including the user-interaction loop. main()
also declares the
variables n1
, n2
, and n3
for the three integers that the program
will process, and it provides initial values for those variables.
Compile and run the program, and you should see the following output:
The current numbers are: 2 4 6 (0) Enter new numbers (1) Find the largest (2) Compute the sum (3) Compute the range (largest - smallest) (4) Compute the average (5) Print the numbers in ascending order (6) Quit Enter your choice:
At the moment, the only supported options are options 0 and 6, so feel free to try them out!
Your tasks Start by reading over the starter code that we’ve given you. Make sure that you understand it.
Then add support for menu options 1-5 so that they perform the specified operations on the three numbers.
Important notes:
-
You must implement a separate helper method for each option. In addition, you should add appropriate code to
main
to handle each option – calling the appropriate helper method, and taking whatever additional steps are needed. -
Each helper method must take the three numbers as parameters. The names of the methods are up to you, but you should of course pick names that describe what the methods are supposed to do.
-
The helper methods for options 1-4 must not do any printing. Rather, they should return the appropriate result, and the printing of the result should be done in
main
. You should select the appropriate return type for each method, based on the value it is supposed to compute. Options 1-3 should produce an integer, while option 4 should produce a floating-point number. -
Your helper method for option 5 should do its own printing – printing the numbers in ascending order, separated by spaces. This helper method should not return a value.
-
There are one or more cases in which one of the helper methods can be simplified by having it call one of the other helper methods to obtain a partial result. For full credit, you should do this whenever possible to avoid duplicating code unnecessarily.
-
You may not use methods from any libraries other than the built-in
Math
library, although usingMath
is not required. Refer to the Math API for details.
A sample run can be found here. Please match the formatting of the results in that file as closely as possible.
Submitting Your Work
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.
Pair-optional problem
If you chose to work on Problem 7 with a partner, both you and your partner should submit your own copy of your joint work, along with your individual work on the other two problems.
You should submit only the following files:
- SimpleStats.java
Make sure that you do not try to submit a .class
file or a file
with a ~
character at the end of its name.
Here are the steps:
-
Login to Gradescope as needed by clicking the link in the left-hand navigation bar, and then click on the box for CS 112.
-
Click on the name of the assignment (
PS 1: Part II
) in the list of assignments. You should see a pop-up window with a box labeled DRAG & DROP. (If you don’t see it, click the Submit or Resubmit button at the bottom of the page.) -
Add your files to the box labeled DRAG & DROP. You can either drag and drop the files from their folder into the box, or you can click on the box itself and browse for the files.
-
Click the Upload button.
-
You should see a box saying that your submission was successful. Click the
(x)
button to close that box. -
The Autograder will perform some tests on your files. Once it is done, check the results to ensure that the tests were passed. If one or more of the tests did not pass, the name of that test will be in red, and there should be a message describing the failure. Based on those messages, make any necessary changes. Feel free to ask a staff member for help.
Note: You will not see a complete Autograder score when you submit. That is because additional tests for at least some of the problems will be run later, after the final deadline for the submission has passed. For such problems, it is important to realize that passing all of the initial tests does not necessarily mean that you will ultimately get full credit on the problem. You should always run your own tests to convince yourself that the logic of your solutions is correct.
-
If needed, use the Resubmit button at the bottom of the page to resubmit your work. Important: Every time that you make a submission, you should submit all of the files for that Gradescope assignment, even if some of them have not changed since your last submission.
-
Near the top of the page, click on the box labeled Code. Then click on the name of each file to view its contents. Check to make sure that the files contain the code that you want us to grade.
Important
-
It is your responsibility to ensure that the correct version of every file is on Gradescope before the final deadline. We will not accept any file after the submission window for a given assignment has closed, so please check your submissions carefully using the steps outlined above.
-
If you are unable to access Gradescope and there is enough time to do so, wait an hour or two and then try again. If you are unable to submit and it is close to the deadline, email your homework before the deadline to your instructor.