Problem Set 1
due by 11:59 p.m. Eastern time on Tuesday, February 4, 2024
Preliminaries
In your work on this assignment, make sure to abide by the collaboration policies of the course.
If you have questions while working on this assignment, please
come to office hours, post them on Piazza, or email cs112-staff@cs.bu.edu
.
Make sure to follow the instructions outlined at the end of Part I and Part II when submitting your assignment.
Part I
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 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
ps1
within yourcs112
folder, and put all of the files for this assignment in that folder.
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 in your
ps1
folder. 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
-
The following program has many syntax errors:
import java.util.*; Public class Problem1: /* * This static method should take an integer x and return: * x + 1 if x is even * the unchanged value of x when x is odd */ public static makeOdd(x) { if x % 2 = 0: x =+ 1 return x; } public void main(String args) { { console = Scanner(System.in) System.print('Enter an integer x: ') int x = Scanner.nextInt() System.println("makeOdd(x) = ", makeOdd(x)); console.close(); } }
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
makeOdd
withx
as its input, and print the value returned by that method.makeOdd
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 6:
Enter an integer x: 6 makeOdd(x) = 7
And here’s what it should look like if the user enters 9:
Enter an integer x: 9 makeOdd(x) = 9
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
.
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 a = 10; int b = 4; double c = 4; double d = 4.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.
-
a + d
-
a + "d"
-
b / a
-
c / a
-
d / a
-
a / b * d
-
(double)(a / b)
-
(double)a / b
-
1 + 2 + "3"
-
1 + "2" + 3
-
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 <= 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");
-
(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
.)-
3 3 3
-
3 4 5
-
3 5 2
-
5 4 3
-
5 4 7
-
4 4 3
-
-
(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) { y += x; x = 10 - y; System.out.println(x + " " + y); return x; } public static void main(String[] args) { int x = 6; int y = 3; System.out.println(x + " " + y); y = compute(x, y); System.out.println(x + " " + y); x = compute(y, x) + 1; System.out.println(x + " " + y); compute(x, 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 the base
b
and heighth
of a triangle and computes and returns the area of the triangle as a real number (i.e., one that could have a fractional part). (Recall: The area of a triangle is the product of its base and height, divided by 2.)public _____________ triArea(______________________) { double area = ___________________; __________________; }
For example:
- the method call
triArea(3, 6)
should return9.0
- the method call
triArea(7, 5)
should return17.5
Note that the body of the method should be exactly two lines: one line that assigns the appropriate expression for the area to to the variable
area
, and a second line that returns the value ofarea
.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("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.
-
(3 points) Consider the following method:
public static void mulFive(int n) { for (int mul = 5; mul <= n; mul += 5) { System.out.println(mul); } }
When the input
n
is a positive integer, this method prints all multiples of 5 less than or equal ton
. For example,mulFive(25)
would print5 10 15 20 25
If
n
is less than 5, 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 = 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.
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 in yourps1
folder. -
Login to Gradescope by clicking the link in the left-hand navigation bar. When logging in, make sure that you use the School Credentials option and select Boston University.
-
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 an insulin dosage
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.
Some people with type I diabetes inject insulin before each meal in order to stabilize their blood-sugar level. The amount of insulin that is required depends on several factors. This problem asks you to complete a simple program that allows the user to compute the amount of insulin that they should inject.
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: InsulinDosage.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
Insulin.java
file that you downloaded in step 2. -
Click on the name
InsulinDosage.java
, which will open an editor window for that file. You will see that we’ve given you the beginnings of the program. Make sure to complete the comments at the top of that file.
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 variablescurrentSugar
,targetSugar
,carbEquiv
,carbConsume
andexercise
. At the moment, each of these assignment statements assigns the number0
. For example, here is the first of the three assignments:int currentSugar = 0;
You should replace the
0
in each of the assignment statements 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 variables to compute the correct dosage of insulin, using the following formula:currentSugar - targetSugar carbConsume dosage = -------------------------- + ----------- - exercise 55 carbEquiv
For example, assume that a person enters the following values:
- current blood sugar: 210
- target blood sugar: 100
- carbohydrate equivalency: 10
- carbohydrates to consume: 60
- amount of exercise: 2
For this person, the program should perform the following computation:
(210 - 100) 60 dosage = --------- + -- - 2 55 10 = 110 --- + 6 - 2 55 = 2 + 6 - 2 = 6
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 dosage 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
dosage
variable (and any other variables that you may use for intermediate results) and in the expressions that you construct for your computations.
-
Display the appropriate message, which depends on the value of the computed dosage as follows:
-
If the computed dosage is exactly 1.0, the program should print the following message:
recommended dosage: 1 unit
Note that the dosage is printed without a decimal, and that the final word printed is
unit
, notunits
. -
If the computed dosage is greater than 0.0 and is a whole number other than 1.0, the program should still print the dosage without a decimal, but the final word should be
units
with ans
at the end. For example, if the computed dosage is 6.0, the program should print:recommended dosage: 6 units
-
If the computed dosage is greater than 0.0 and is not a whole number (i.e., it has a fractional part), the program should print the full computed value, including all of the digits after the decimal point. For example, if the computed dosage is 7.125, the program should print:
recommended dosage: 7.125 units
-
If the dosage is less than or equal to 0.0, the program should print the following message:
recommended dosage: 0 units
Notes:
-
There is more than one way to test if the computed dosage 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 the examples that we have shown above.
-
-
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
.Note: When your run the program, you may need to click on the Terminal area of VS Code in order to input the five numbers.
Problem 6: Computing area from diameter
15 points; individual-only
This problem involves writing a program that computes the area of a circular piece of land, based on its diameter.
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
Circular.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
Circular
that will serve as a container for your program. -
Inside the
Circular
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 code to obtain an integer representing the diameter of the piece of land (specified to the nearest foot) and store it in an appropriate variable.
Use a
print
statement with an appropriate prompt, and then use theScanner
that you created at the start ofmain
to get the diameter 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. -
Use the value entered for the circle’s diameter to compute its area in square feet as a real number, and store the result in an appropriate variable. Make the computation as precise as possible.
Recall that:
-
The radius of a circle is half of its diameter.
-
The area of a circle is π times the radius squared (i.e., π * radius * radius). Use the value of π available in Java’s built-in
Math
class, which you can obtain by writingMath.PI
For example, if the diameter is 10 feet, the radius is 5 feet, and thus the area is
Math.PI
times 5 squared or 78.53981633974483 square feet. -
-
Display the approximate area of the circle in two forms:
-
in square feet rounded to the nearest integer; to perform the necessary rounding, make a call to the built-in
Math.round
method.Note:
Math.round
returns a value of typelong
, which is the data type that Java provides for large integers. As a result, in order to store the return value in a variable of typeint
, you will need to perform a type cast. -
as a whole number of square yards, with the remaining area expressed as an integral number of square feet. 1 square yard is 3 square feet, so you can convert from square feet to square yards by dividing by 9.
For example, if the user enters a diameter of 10, the output should look like this:
The area of the circle is approximately: 79 square feet 8 square yards plus 7 square feet
Note that the final line of results stems from the fact that 79 divided by 9 is 8 with a remainder of 7.
Make sure that the format of your results matches the example that we have shown above.
-
-
Close the
Scanner
object’s connection to the keyboard by calling the object’sclose()
method. See the starter code for the previous problem for an example of how to do this. -
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. Don’t forget to include your partner’s name and email in the comments at the top of the file.
You should submit only the following files:
InsulinDosage.java
Circular.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 by clicking the link in the left-hand navigation bar, and then click on the box for CS 112. When logging in, make sure that you use the School Credentials option and select Boston University.
-
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