Skip to content

Homework 2: Logic

This assignment is about if/else statements, while loops, relational operators, conditional operators, and the Math class. You will also gain experience writing documentation and testing your programs with JUnit.

Important

Starter code is provided for this homework. Download and open (extract) hw2.zip. Move the hw2 folder into your CS159/src/hws folder.

Please review the Grading Criteria at the end of this page before you start programming.

Learning Objectives

After completing this homework, you should be able to:

  • Write if/else statements: simple, nested, and chained.
  • Apply logic operators (&&, ||, !) to boolean expressions.
  • Use a while loop to compute a mathematical function.
  • Write documentation comments for classes and methods.

This assignment must be completed individually. Your work must comply with the JMU Honor Code. Authorized help is limited to general discussion on Piazza, the lab assistants assigned to CS 159, and the instructor. Copying code from someone else, including the use of generative AI, is prohibited and will be grounds for a reduced or failing grade in the course.

Writing Javadoc comments

The starter code does not include any Javadoc comments. One objective for this assignment is for you to learn how to write Javadoc comments. Please read and follow the Javadoc Guidelines. Some of the Javadoc comments for HW2 are provided in the instructions below. See the HW1 files (especially UnitConversion.java and UnitConversionTest.java) for more examples. Javadoc comments are not required for test methods.

Testing with JUnit (optional)

The starter code includes an example Test class for each exercise. The Test classes show how to call each method in the assignment. You are strongly encouraged to write additional tests and run JUnit before submitting your code to Gradescope. See the instructions from Lab01 about running unit tests. You do not need to submit your test files.

Exercise 2.1 Exact Change

When you shop at a grocery or retail store, someone scans your items so that a computer can determine the total purchase amount. Customers who pay in cash often use whole dollars, rather than provide the exact amount in coins. That's where your program comes into the story. You are to implement an algorithm for an automatic change dispenser.

Write a class named ExactChange that includes the following method:

/**
 * Print how to make change. To avoid rounding errors, all arithmetic
 * is performed with integers.
 *
 * @param total the total charge for the purchase
 * @param paid the amount paid (in whole dollars)
 */
public static void printCoins(double total, int paid)

This method calculates the amount of change due and prints out how many dollars, quarters, dimes, nickels, and pennies should be dispensed. For example, printCoins(5.32, 10) prints:

4 dollars
2 quarters
1 dime
1 nickel
3 pennies

Do not print any coins with a zero count. If the count is one, display the coin's singular name (dollar, quarter, dime, nickel, penny) instead of the coin's plural name (dollars, quarters, dimes, nickels, pennies). For example, printCoins(0.74, 1) prints:

1 quarter
1 penny

Warning

Your solution must not use any loops. For this exercise, Gradescope will automatically reject submissions containing words like for and while.

Hint 1: You might find it easier to calculate the number of each coin first, before outputting any results. Doing so will make the arithmetic and logic patterns more clear in the source code.

Hint 2: To avoid floating-point errors, convert the amount of change to an integer. For example, $1.24 is 124 cents. Use Math.round() and cast the result to an int.

Exercise 2.2 Interstate Numbers

In the United States, interstate highways follow a specific numbering system based on the type and direction:

  • One- and two-digit numbers are reserved for "primary" interstates (Ex: I-95). North-south routes are assigned odd numbers, and east-west routes are assigned even numbers.

  • Three-digit numbers are for "auxiliary" interstates (Ex: I-495). If the first digit is even, the road is typically a "beltway" around a major city. If the first digit is odd, the road is typically a "spur" that deviates from a primary interstate.

Define a class named InterstateNumbers with a getInfo() method that takes an integer and returns a string. There are five possible return values, depending on the parameter value:

  • "primary east-west" – even number with one or two digits (Ex: I-70)
  • "primary north-south" – odd number with one or two digits (Ex: I-25)
  • "beltway for I-??" – three-digit number with even first digit (Ex: I-280)
  • "spur for I-??" – three-digit number with odd first digit (Ex: I-395)
  • "invalid" – if the given interstate number is not between 1 and 999

Beltway and spur results must include the last two digits of the interstate number instead of ??. For example, getInfo(395) would return "spur for I-95".

Exercise 2.3 Yahztee Logic

Yahtzee is a dice game played by rolling five six-sided dice. The objective is to score points by making certain combinations.

Rolling two of one number and three of another number is called a full house. For example, two 2's and three 5's:

Full house with dice values: 2, 2, 5, 5, 5.

Rolling five sequential numbers (Ex: 1-2-3-4-5 or 2-3-4-5-6) is called a large straight. Rolling four sequential numbers is called a small straight, as shown below:

Small straight with dice values: 1, 3, 4, 5, 6.

Write a class named YahzteeLogic that implements the following methods. You may assume that the integers represented by c1 to c6 add up to 5. Each integer is between 0 (meaning no dice) and 5 (meaning all dice).

/**
 * Check for three of a kind and a pair.
 *
 * @param c1 number of 1's rolled
 * @param c2 number of 2's rolled
 * @param c3 number of 3's rolled
 * @param c4 number of 4's rolled
 * @param c5 number of 5's rolled
 * @param c6 number of 6's rolled
 * @return whether the dice represent a full house
 */
public static boolean isFullHouse(
        int c1, int c2, int c3, int c4, int c5, int c6)
/**
 * Check for four or five sequential dice.
 *
 * @param small true for small straight mode
 * @param c1 number of 1's rolled
 * @param c2 number of 2's rolled
 * @param c3 number of 3's rolled
 * @param c4 number of 4's rolled
 * @param c5 number of 5's rolled
 * @param c6 number of 6's rolled
 * @return true if the dice have a straight
 */
public static boolean isStraight(boolean small,
        int c1, int c2, int c3, int c4, int c5, int c6)

Note: The small parameter of isStraight() determines whether the method should look for a small straight or a large straight.

Hint: This exercise is all about && and || operators. Avoid writing unnecessary if statements. The sample solution has only one if statement in the entire file.

Exercise 2.4 Collatz Conjecture

The Collatz conjecture is one of the most famous unsolved problems in mathematics. The basic idea is:

  • Start with any positive integer.
  • Repeat the following step until the integer is 1:
    • If the integer is even, divide the integer by 2.
      Otherwise multiply the integer by 3 and add 1.

Dr. Collatz proposed that this process will eventually reach the number 1, regardless of which positive integer is chosen initially. No one has been able to prove or disprove this conjecture!

However, you can write a program to simulate and study the process. Write a class named CollatzConjecture that implements the following method.

public static int countSteps(int n)

The method should run the Collatz process and count how many times the step runs. Return the number of steps, or return -1 if the parameter n is not positive.

For example, the parameter 3 produces the sequence 3, 10, 5, 16, 8, 4, 2, 1. In this sequence, the logic step was repeated 7 times. So the return value of countSteps(3) is 7.

Grading Criteria

Your code will first be graded by Gradescope and then by the professor. The grade you receive from Gradescope is the maximum grade that you can receive on the assignment.

After the due date, the professor may manually review your code. At that time, points may be deducted for inelegant code, inappropriate variable names, bad comments, etc.

Your code must compile with the official tests for you to receive any points. For full credit, your code must also pass a Checkstyle audit.

Gradescope will provide you with hints but might not completely identify the defects in your submission. You are expected to test your own code before submitting.

There is no limit on the number of submissions and no penalty for excessive submissions. Points will be allocated as follows:

Criterion Points Details
Compile 0 pts Success Required
CompileOfficialTests 0 pts Success Required
Style 20 pts Partial Credit Possible
OfficialTests 80 pts Partial Credit Possible