Old version
This is the CS 112 site as it appeared on May 12, 2022.
Problem Set 1
due by 11:59 p.m. Eastern time on Tuesday, February 1, 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
40 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 file
The problems from Part I will all 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
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 Part I.
Problem 1: Java programming basics
10 points total; 5 points each part; individual-only
Using folders
You should create a separate folder for each assignment.
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 ps1
within your cs112
folder
for your work on this assignment, and put all of the files for
PS 1 in that folder.
-
The following program has many syntax errors:
import java.util.*; public Problem1 { /* * This static method should take an integer x and return: * - the opposite of x when x is negative * - 10 more than x when x is non-negative and even * - the unchanged value of x when x is non-negative and odd */ public static adjust(x) if x < 0: x * -1; elif x % 2 = 0: x =+ 10 return x; } public main(String[] args): Scanner console = Scanner() System.out("Enter an integer x: ") x = console.nextInt(); System.out('adjust(x) = ', adjust(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
adjust
withx
as its input, and print the value returned by that method.adjust
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 -3:
Enter an integer x: -4 adjust(x) = 4
And here’s what it should look like if the user enters 6:
Enter an integer x: 6 adjust(x) = 16
Debugging in VS Code
We encourage you to use VS Code to help you to debug this program. Here are the steps:-
If you haven’t already done so, create a folder named
ps1
for your work on this assignment. -
Download the following file: Problem1.java
Make sure to put the file in your
ps1
folder. If your browser doesn’t allow you to specify where the file should be saved, try right-clicking on the link above and choosing Save as... or Save link as..., which should produce a dialog box that allows you to choose the correct folder for the file. -
In VS Code, select the File->Open Folder or File->Open menu option, and use the resulting dialog box to find and open the folder that you created for this assignment. (Note: You must open the folder; it is not sufficient to simply open the file.)
The name of the folder should appear in the Explorer pane on the left-hand side of the VS Code window, along with the name of the
Problem1.java
file that you downloaded above. -
Click on the name
Problem1.java
, which will open an editor window for that file. -
Make whatever edits are needed to allow you to compile and run the program. You can try to run the program by using the F5 key, or by right-clicking the name of the program in the Explorer pane and choosing
Run
orRun Java
.Note: VS Code may show you a message that looks like this:
Resource leak: 'console' is never closed
You can ignore this message. It is warning, not an error, and it will not keep the program from compiling and running.
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 x = 23; double y = 4; int z = 4; double n = 14.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.
-
x / y
-
x / z
-
x + y
-
"x" + "y"
-
x % 6
-
y == z
-
(int)(n / z * z)
-
(int)n / z * z
-
11 + 2 + "CS"
-
"CS" + 11 + 2
-
Problem 2: Conditional execution
10 points total; 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 <= c) { if (c > b && a < 5) { System.out.println("Terriers"); } else { System.out.println("Eagles"); } System.out.println("Crimson"); } else if (b < a) { if (b == c) { System.out.println("Huskies"); } else if (b > c) { System.out.println("Engineers"); } else { System.out.println("Bears"); } if (a < c) { System.out.println("Lions"); } } else { System.out.println("Big Green"); if (a == b || b > 7) { System.out.println("Big Red"); } if (!(b > c)) { System.out.println("Quakers"); } if (a != c) { System.out.println("Bulldogs"); } } System.out.println("Let's go!");
-
(6 points) In section 2-1 of
ps1_partI
(see above), state the output that would result from each of the following sets of inputs. (In each case, the first number will be assigned to the variablea
, the second number will be assigned tob
, and the third number will be assigned toc
.)-
1 2 3
-
4 1 4
-
3 1 2
-
5 8 3
-
5 4 4
-
3 5 2
-
-
(4 points) 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 3: Static methods
10 points total; individual-only
-
(5 points) Consider the following Java program, which includes two static methods:
public class TracingMethodCalls { public static int compute(int x, int y) { x += 3; y = 2*y - x; System.out.println(x + " " + y); return x; } public static void main(String[] args) { int x = 1; int y = 3; System.out.println(x + " " + y); x = compute(x, y); System.out.println(x + " " + y); compute(y, y); System.out.println(x + " " + y); y = 3 + 4 * compute(y, x); System.out.println(x + " " + y); } }
In section 3-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.
-
(5 points) Fill in the blanks below to create a static method that takes as parameters two integers representing a person’s weight
w
(specified to the nearest pound) and heighth
(specified to the nearest inch), and that computes and returns the person’s body mass index (BMI) as a real number (i.e., one that could have a fractional part).public _____________ bmi(______________________) { double result = ___________________; __________________; }
When computing the BMI, you should use the following formula:
720 * w BMI = ------- h * h
For example:
- the method call
bmi(100, 60)
should return20.0
- the method call
bmi(162, 72)
should return22.5
Note that the body of the method should be exactly two lines: one line that assigns the appropriate expression for the BMI to the variable
result
, and a second line that returns the value ofresult
.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 4: Loops
10 points total; individual-only
-
(3 points) In
ps1_partI
, we have included the following partial code fragment:for (____________; ____________; ____________) { System.out.println("Twenty two!"); }
Fill in the blanks to create a loop that repeats the message “Twenty two!” 2022 times. Use the approach for obtaining N repetitions that we discussed in lecture.
-
(3 points) Consider the following method:
public static void countDown(int n) { for (int count = n; count >= 1; count--) { System.out.println(count); } }
When the input
n
is a positive integer, this method “counts down” fromn
, printing the integers fromn
down to 1. For example,countDown(5)
would print5 4 3 2 1
If
n
is less than or equal to 0, the method does not print anything.We have included the original method in
ps1_partI
. Rewrite it so that it uses awhile
loop instead of afor
loop. -
(4 points) Consider the following code fragment:
for (int i = 1; i <= 4; i++) { System.out.println("** " + i + " **"); for (int j = 3; j >= 0; j++) { System.out.println(i + " " + j); } }
Modify this fragment to make it produce the following output:
** 1 ** 1 3 1 2 1 1 ** 2 ** 2 3 2 2 ** 3 ** 3 3
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.
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
cs112-staff@cs.bu.edu
Part II
30 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.
-
You should not use any built-in Java classes or methods that we have not covered in the lecture notes, unless we explicitly instruct you to do so.
-
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 minimum we expect that your submitted code will compile and run. If your code does not compile during our tests, you will not receive any credit for that specific problem. If there are lines in your program that prevent it from compiling, remove them or turn them into comments by putting two slashes (
//
) at the start of the each of the problematic lines. If you are unsure about how to get your program to compile, feel free to ask us for help.
Problem 5: Computing the cost of a car trip
15 points total; pair-optional
This is the only problem of the assignment that you may complete with a partner. See the rules for working with a partner on pair-optional problems for details about how this type of collaboration must be structured.
Important
Some of the points for Part II will be based on your use of 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.
This problem asks you to complete a simple program that allows a user to compute the cost of a trip by car. The cost is based on three inputs: the price of gas, the car’s MPG (miles per gallon) rating, and the distance of the trip.
Getting started
-
If you haven’t already done so, create a folder named
ps1
for your work on this assignment. You can find instructions for doing so here. -
Download the following file: TripComp.java
Make sure to put the file in your
ps1
folder. If your browser doesn’t allow you to specify where the file should be saved, try right-clicking on the link above and choosing Save as... or Save link as..., which should produce a dialog box that allows you to choose the correct folder for the file. -
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 in step 1. (Note: You must open the folder; it is not sufficient to simply open the file.)
The name of the folder should appear in the Explorer pane on the left-hand side of the VS Code window, along with the name of the
TripComp.java
file that you downloaded in step 2. -
Click on the name
TripComp.java
, which will open an editor window for that file. You will see that we’ve given you the beginnings of the program.
Completing the program
-
Start by reading over the starter code that we’ve given you. Make sure that you understand it.
-
Complete the assignment statements in the
main
method for the variablesgasPrice
,mpgRating
, anddistance
. At the moment, each of these assignment statements assigns the number0
. For example, here is the first of the three assignments:int gasPrice = 0;
You should replace the
0
in each of the three assignments with a call to aScanner
method that reads an integer entered by the user from the keyboard.Important: You must use the
Scanner
object created at the start of themain
method, and you may not create an additionalScanner
object.You may assume that all of the values entered by the user are valid values, and thus you do not need to perform any checking for problematic values.
-
Complete the
main
method so that it uses the values of the variablesgasPrice
,mpgRating
, anddistance
to compute the cost of the trip in dollars using the following formula:gasPrice distance cost = -------- * --------- 100 mpgRating
For example, if gas costs 300 cents per gallon, the car’s MPG rating is 25 miles per gallon, and the trip is 200 miles, the program should perform the computation
300 200 --- * --- = 24 100 25
Notes:
-
The formula that we have given you uses standard mathematical notation. You will need to use the appropriate Java operators and appropriate numeric literals in your code.
-
You may find it helpful to compute the cost in stages by first computing some of the components of the formula – storing their values in one or more variables that you declare – and then combining those components to compute the final result.
-
In the example above, the cost happens to be an integer, but that won’t always be the case, and you should make your computation as precise as possible. This means that you will need to be careful with the type that you select for your
cost
variable (and any other variables that you may use for intermediate results) and in the expressions that you construct for your computations.
-
-
Display the result in the appropriate format.
-
If the cost is an integer (i.e., a whole number of dollars, with no additional cents), then the cost should be printed without a decimal. For example, here is a sample run in which the user enters the values mentioned in the above example:
gas price in cents: 300 MPG rating of the car: 25 distance of the trip: 200 The cost of the trip is $24.
Note: The first three lines above are from the portion of the program that uses
Scanner
methods to get the necessary values from the user. You should not echo/re-print the user’s inputs. The only new print statement that you should add is the one for the cost of the trip. -
If the cost is not a whole number of dollars, then the cost should be printed in the form
$d.cc
, whered
is the number of dollars, andcc
is the number of cents rounded to two places after the decimal. For example, here is another sample run in which the cost is not a whole number:gas price in cents: 300 MPG rating of the car: 20 distance in miles: 210 The cost of the trip is $31.50.
To ensure that you always get two places after the decimal, you should make a call to the method called
formattedCost
that we have provided. Read the comments that precede that method to see what it does.
Notes:
-
There is more than one way to test if the computed cost is a whole number. You may want to consider using a type cast in some way.
-
Make sure that the format of your results matches what we have shown above. In particular, you should have a dollar sign (
$
) immediately before the price and a period (.
) immediately after it.
-
-
Test your program on a variety of inputs to make sure that you don’t have any logic errors in your code.
Remember that you can run the program by using the F5 key, or by right-clicking the name of the program in the Explorer pane and choosing
Run
orRun Java
.Notes:
-
VS Code may show you a message that looks like this:
Resource leak: 'scan' is never closed
You can ignore this message. It is warning, not an error, and it will not keep the program from compiling and running.
-
When your run the program, you may need to click on the Terminal area of VS Code in order to input the three numbers.
-
Problem 6: Computing the length of a ladder
15 points; individual-only
Your friend needs to use a ladder to reach a certain point on the outside of their house. To avoid adjusting the ladder once it’s in the air, they ask you to create a program that allows them to precompute the required length of the ladder.
Getting started
-
As needed, open your
ps1
folder using the File->Open Folder or File->Open menu option in VS Code. -
Select File->New File, which will open up an empty editor window.
-
Select File->Save, and give the new file the name
Ladder.java
.
Writing the program
-
Add comments at the top of the new file that include:
- a brief desciption of what the program is supposed to do.
- your name and email address
See the comments that we provided in the starter code for previous problem for an example of what they should look like.
-
Below the comments – and before any class header – add an
import
statement for thejava.util
package, as we did in the starter code for the previous problem. Including thisimport
statement will allow you to create aScanner
object in your program. -
Create a class named
Ladder
that will serve as a container for your program. -
Inside the
Ladder
class, add amain
method with the usual header. -
Start the
main
method by creating aScanner
object for getting user inputs from the keyboard and assigning it to an appropriate variable. -
Next, add statements to read the following values from the user and store them in appropriate variables:
-
an integer representing the height of the point the ladder needs to reach (specified to the nearest foot)
-
an integer representing the angle in degrees at which the ladder will be positioned (specified to the nearest degree)
Use a
print
statement with an appropriate prompt for each input, and use theScanner
that you created at the start ofmain
to get each input from the user.Important: You must use the
Scanner
object created at the start of themain
method, and you may not create an additionalScanner
object. -
-
Convert the value entered for the angle in degrees to an equivalent real number in radians:
angle * Math.PI radians = --------------- 180
where
angle
is the angle in degrees that was entered by the user andMath.PI
is a built-in constant that Java provides for the value of π. Make the computation as precise as possible. -
Compute the required length of the ladder as a real number as follows:
height length = ----------------- Math.sin(radians)
where
height
is the height in feet entered by the user andMath.sin
is a built-in method that Java provides for computing the sine of an angle. Make the computation as precise as possible. -
Report the length of the ladder in three forms:
- in feet as a real number
- in yards as a real number (yards = feet / 3)
- as an integral number of yards, with the remaining length expressed in feet as a real number
For example, if the height is 20 feet and the angle is 60 degrees, the output should look like this:
The required length is: 23.094010767585033 feet 7.698003589195011 yards 7 yards and 2.094010767585033 feet
-
Test your program on a variety of inputs to make sure that you don’t have any logic errors in your code.
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 standards and followed all guidelines regarding format, layout, spaces, blank lines, and comments.
-
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 5 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 problem.
You should submit only the following files:
TripComp.java
Ladder.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
cs112-staff@cs.bu.edu