CMP 326: Introduction to Java Programming Homework Problems
Lehman College, City University of New York
Fall 2014

  • Problem Set 1a

    1. Circles

      Convert the following Python 3 program into Java. You might want to run the Python program to see what the output should be.

      def main():
          rad1 = 18
          rad2 = 19
          pi = 3.14
          print( "The diameter of the first circle is", 2*rad1 * pi )
          print( "The diameter of the second circle is", 2*rad2 * pi )
          print( "The area of the first circle is", rad1 * rad1 * pi )
          print( "The area of the second circle is", rad2 * rad2 * pi )
          print( "The ratio of the two radii is", rad1 / rad2 )

      Name this class Circles
      Place the class in the edu.cuny.lehman.cmp326 package.

    2. Mad Libs

      A madlib is a word game played by one person asking the others for specific types of words (i.e. noun, verb, exclamation), and using them to fill in the blanks in a sentence. This results is a bizarre, but hopefully funny, sentence. (Wikipedia page on Mad Libs)

      Write a program that asks the user for the required type of word to fill in four blanks in a sentence or two. The program should then display the filled in sentence(s) to the user. You may use the example sentence below, or make up your own. As in problem 1.1, you may use either a GUI or the keyboard scanner and output console.

      Example output might be:

      Enter an adjective: white
      Enter an adjective: silly
      Enter a person: aunt
      Enter an event: Santa Claus parade
      
      Here's your sentence:
      It was a white and silly night, but I still managed to make it to the house of my aunt to watch the Santa Claus parade.

      Name this class MadLibs
      Place the class in the edu.cuny.lehman.cmp326 package.

  • Problem Set 1b

    1. Feet to Yards

      Write a program that asks the user for distance in feet and prints the number of yards and feet (assume that there are 3 feet to the yard). For example, if the user entered, 10, your program would output 3 yards 1 feet. Note that you should use "yards" and "feet" for all inputs (even in the cases where it is grammatically incorrect).

      Name this class LengthConverter
      Place the class in the edu.cuny.lehman.cmp326 package.

    2. Stone to Kg Converter

      Convert the following pseudocode into Java. Debug it and make sure there are no errors in the pseudocode.

      // converts from stone to kg. 1 stone == 14 lbs. 1 lb. == 0.453592 kg.
      main(){
          get input from user and assign to stones
          lbs = stones * 14
          kg = lbs * 0.453592
          print out total number of kilograms
      }

      Name this class MassConverter
      Place the class in the edu.cuny.lehman.cmp326 package.

  • Problem Set 2a

    Note: as announced, you can ignore the instructions to write separate functions in Problem Set 2a
    1. Temperature Converter

      Write a (static) method that allows the user to convert a temperature, given in degrees, from either Celsius to Fahrenheit or Fahrenheit to Celsius. Use the following formulas:

      Degrees_C = 5(Degrees_F - 32)/9
      Degrees_F = (9/5)Degrees_C + 32

      Prompt the user to enter a temperature followed by either “C” or “c” for Celsius or a temperature followed by “F” or “f” for Fahrenheit. Convert the temperature to Fahrenheit if Celsius is entered, or to Celsius if Fahrenheit is entered. Display the result in a readable format. If anything other than a number followed by “C”, “c”, “F”, or “f” is entered, print an error message and stop.

      Name this class TemperatureConverter
      Place the class in the edu.cuny.lehman.cmp326 package.

      Hint: Since 9 and 5 are both ints, (9/5) will evaluate to 1 in Java, which is not what we want.

    2. BART Fare

      Write a function that takes as two parameters: the zone and the ticket type, and returns the BART fare.

      • If the zone is 2 or smaller and the ticket type is "adult," the fare is 20.
      • If the zone is 2 or smaller and the ticket type is "child," the fare is 10.5.
      • If the zone is 3 and the ticket type is "adult," the fare is 30.5.
      • If the zone is 3 or 4 and the ticket type is "child," the fare is 20.
      • If the zone is 4 and the ticket type is "adult," the fare is 43.
      • If the zone is greater than 4 or if the ticket type is neither "adult" not "child", return a negative number (since your calculator does not handle inputs that high).

      Include a main() that calls your function several times to demonstrate that it works. Make sure to test for inappropriate inputs.

      Name this class BARTFare
      Place the class in the edu.cuny.lehman.cmp326 package.

  • Problem Set 2b

    1. Hand Shakes

      Suppose we attend a party. To be sociable, when we arrive, we will shake hands with everyone who is already at the party. Write a program that prompts the user for the total number of guests at a party. Using a for loop, your program will compute and display the number of handshakes that occur as each guest arrives. Your program should also compute and display the total number of handshakes that occur after all guests have arrived. (Hint Upon arrival, each person shakes hands with everyone that is already there. You can assume that there is only one host for the party). Your output format should exactly match this output format:

      How many guests are invited to the party: 5
      When Guest 1 arrives, Handshakes=1, Total Handshakes=1
      When Guest 2 arrives, Handshakes=2, Total Handshakes=3
      When Guest 3 arrives, Handshakes=3, Total Handshakes=6
      When Guest 4 arrives, Handshakes=4, Total Handshakes=10
      When Guest 5 arrives, Handshakes=5, Total Handshakes=15

      Name this class HandShakes
      Place the class in the edu.cuny.lehman.cmp326 package.

    2. Coin Tosses

      (Exercises #10, Page 249) Write a program that will compute statistics for eight coin tosses. The user will enter either an h for heads or a t for tails for the eight tosses. The program will then display to total number and percentages of heads and tails. Use the increment operator to count each h or t that is entered. For example, a possible sample dialogue between the program and the user might be:

      For each coin toss enter either h for heads or t for tails.
      Toss 1: h
      Toss 2: t
      Toss 3: t
      Toss 4: h
      Toss 5: t
      Toss 6: h
      Toss 7: t
      Toss 8: t
      Number of heads: 3
      Number of tails: 5
      Percent heads: 37.5
      Percent tails: 62.5

      Name this class CoinTosses
      Place this class in the edu.cuny.lehman.cmp326 package.

  • Problem Set 3a


    1. Check Words

      For all the following words, if you move the first letter to the end of the word, and then spell the word the result backwards, you will get the original word:

      banana dresser grammar potato revive uneven assess

      Write a program that asks the user for one word at a time and determines whether it has this property. Continue asking for and testing words until the user enters the word quit. Treat upper case letters as lowercase letters.

      Name this class CheckWords
      Place this class in the edu.cuny.lehman.cmp326 package.

    2. Bank Interest

      Write a program that prompts the user for a beginning bank balance and an interest rate. The program will display the value of the account at the end of each year for 10 years. The output should show the value of the account for three different methods of compounding interest:

      1. Annually: The interest is added once per year, at the end of the year. You can assume that the interest is posted exactly one year from the date of deposit.
      2. Monthly: The interest is added once per month, at the end of the month. You can assume that interest is posted exactly one month after the date of deposit. Hint: Be sure to adjust the interest rate for the time period of the interest. If the rate is 5%, you must use (5/12)% in the monthly case.
      3. Daily: The interest is added once per day, at the end of the day. You do not need to worry about leap years, assume that all years have 365 days. Hint: Be sure to adjust the interest rate for the time period of the interest. If the rate is 5%, you must use (5/365)% in the daily case.

      Your program should allow the user to perform the calculation multiple times for different starting balances. A negative starting balance indicates that the user is done.

      Sample output:

      Enter initial balance: 1000
      Enter apr: .05
      After 1 year
      Annually compounded: 1050.0
      Monthly compounded: 1051.16
      Daily compounded: 1051.27
      After 2 years
      Annually compounded: 1102.5
      Monthly compounded: 1104.94
      Daily compounded: 1105.16
      After 3 years
      Annually compounded: 1157.63
      Monthly compounded: 1161.47
      Daily compounded: 1161.82
      After 4 years
      Annually compounded: 1215.51
      Monthly compounded: 1220.9
      Daily compounded: 1221.39
      After 5 years
      Annually compounded: 1276.28
      Monthly compounded: 1283.36
      Daily compounded: 1284.0
      After 6 years
      Annually compounded: 1340.1
      Monthly compounded: 1349.02
      Daily compounded: 1349.83
      After 7 years
      Annually compounded: 1407.1
      Monthly compounded: 1418.04
      Daily compounded: 1419.03
      After 8 years
      Annually compounded: 1477.46
      Monthly compounded: 1490.59
      Daily compounded: 1491.78
      After 9 years
      Annually compounded: 1551.33
      Monthly compounded: 1566.85
      Daily compounded: 1568.26
      After 10 years
      Annually compounded: 1628.89
      Monthly compounded: 1647.01
      Daily compounded: 1648.66
      
      Enter initial balance: 2000
      Enter apr: .05
      After 1 year
      Annually compounded: 1710.34
      Monthly compounded: 1731.27
      Daily compounded: 1733.19
      After 2 years
      Annually compounded: 1795.86
      Monthly compounded: 1819.85
      Daily compounded: 1822.04
      After 3 years
      Annually compounded: 1885.65
      Monthly compounded: 1912.96
      Daily compounded: 1915.46
      After 4 years
      Annually compounded: 1979.93
      Monthly compounded: 2010.83
      Daily compounded: 2013.66
      After 5 years
      Annually compounded: 2078.93
      Monthly compounded: 2113.7
      Daily compounded: 2116.89
      After 6 years
      Annually compounded: 2182.87
      Monthly compounded: 2221.85
      Daily compounded: 2225.42
      After 7 years
      Annually compounded: 2292.02
      Monthly compounded: 2335.52
      Daily compounded: 2339.51
      After 8 years
      Annually compounded: 2406.62
      Monthly compounded: 2455.01
      Daily compounded: 2459.45
      After 9 years
      Annually compounded: 2526.95
      Monthly compounded: 2580.61
      Daily compounded: 2585.54
      After 10 years
      Annually compounded: 2653.3
      Monthly compounded: 2712.64
      Daily compounded: 2718.1
      
      Enter initial balance: -1
      Done.

      Name this class BankInterest
      Place this class in the edu.cuny.lehman.cmp326 package.

      Hint: Remember that an int divided by an int is an int (but you might not want it to be).

  • Problem Set 3b


    1. Get first letters

      Write a program that asks the user to enter a series of five-letter words. Keep asking until the user enters an empty string. If the word they enter is not five letters, don’t use that word, and prompt them again. You will then collect the first letters from each word into a variable, the second letters into a variable, etc. At the end, print the five variables in order.

      Here is some sample output:

      Please enter a five-letter word (<enter> to end): Frank
      Please enter a five-letter word (<enter> to end): banjo
      Please enter a five-letter word (<enter> to end): bank
      That's not five letters!
      Please enter a five-letter word (<enter> to end): hello
      Please enter a five-letter word (<enter> to end): bingo
      Please enter a five-letter word (<enter> to end): wordy
      Please enter a five-letter word (<enter> to end):
      
      Fbhbw
      raeio
      anlnr
      njlgd
      koooy

      Name this class ListCities
      Place the class in the edu.cuny.lehman.cmp326 package.

    2. Guessing game

      Write a guessing game program that asks the user to guess your secret number. If the guess is too high, write a message saying so and ask them to guess again. Similarly, if the guess is too low, write a message saying so and ask them to guess again. If they guess correctly, congratulate them and end the program. You can assume the user will only enter integers.

      You can either fix the secret number in your code, or you can use methods from the class Random to generate a random secret number. You will have to import java.util.Random to use this class.

      Name this class GuessingGame
      Place the class in the edu.cuny.lehman.cmp326 package.

  • Problem Set 4a


    1. Video Game Character

      Write a class for a video game character. The character should have a name, a type (scout, soldier, medic, etc.) and current health. Therefore it needs three attributes:

      • String name
      • String type
      • int health

      This class should have the following methods:

      • GameCharacter( String newName, String newType, newCurHealth )
        —Constructor that takes three inputs
      • changeHealth( int change )
        —A method that changes the health of the character. The character’s health will change by change amount, so it will go down if change is negative, and up if it’s positive. If the health goes below 0, changeHealth should return the String "Your character is dead".

      Name this class GameCharacter. Write a main method to test your code. Each method should be tested at least 3 times.
      Place the class in the edu.cuny.lehman.cmp326 package.

    2. Item Sales part a

      Consider a class that keeps track of the sales of an item. An object of this class will have the attributes (variable names in parentheses):

      • Number sold (numSold)
      • Total sales in dollars (totSales)
      • Total discounts (totDisc)
      • Cost per item (itemCost)
      • Bulk quantity: the number that must be ordered at once to trigger a bulk discount (bulkQuant)
      • Bulk discount percentage: in a bulk order, the percentage discount—i.e. a value of .3 would mean 30% off (bulkDiscPct)

      And the following constructors:

      • ItemSales()
        —Default constructor.
      • ItemSales(double itemCost)
        —Constructor that initializes the itemCost.

      Implement this class in Java. (What types should the variables be? What values should the variables be initialized to in each contructor?) Implement get and set methods for all attributes, as well as a toString method. Now write a main method to test your setters and getters. Make sure you test all the possibilities (e.g., what happens if you try to set a negative cost per item?). Also be sure the output is clear for your users.

      Name these classes ItemSales & ItemSalesDemo
      Place both classes in the edu.cuny.lehman.cmp326 package.

    3. Problem Set 4b


      Item Sales part b

      Now we’ll expand the ItemSales class that was started in part a. Add the following methods:

      • ItemSales(double itemCost, int bulkQuantity, double discountPecentage)
        — Constructor that initializes itemCost, bulkQuatity and discoutPercentage.
      • ItemSales(int bulkQuantity, double discountPercentage)
        —Constructor the initializes bulkQuatity and discoutPercentage.
      • registerSale(n)
        —Records the sale of n items. If n is equal to or larger than the bulk quatity, the cost per item will be reduced by the bulk discount.
      • displaySales()
        —Displays the number sold, the total sales, and total discount.
      • equals(ItemSales otherItem)
        —Compare two ItemSales objects for equality. They will be considered equal if all the attributes are equal.

      Update your main method to test your setters and getters. Make sure you test all the possibilities (e.g., what happens if you try to sell an item that hasn’t had a price set, yet?). Again, be sure the output is clear for your users.

    4. Problem Set 5a


      PersonAddress Class

      Implement a class PersonAddress that represents an entry in an address book. Its attributes are:

      • The first name of the person
      • The last name of the person
      • The email address of the person
      • The telephone number of the person
      It will have methods to
      • Access each attribute
      • Change the email address
      • Change the telephone number
      • Test whether two instances are equal based solely on name
      • Return a String with the information stored in that instance of the PersonAddress class (a toString() method).
      Include a driver program that instantiates at least three objects of type PersonAddress and calls each method at least twice.
    5. Problem Set 5b


      Characterstic

      Consider a class Characteristic that will be used in an online dating service to assess how compatible two people are. Its attributes are:

      • description—A String that identifies the characteristic (for instance pets or hair color)
      • rating—An integer between 1 and 10 (inclusive) that indicates a person’s desire for this characteristic in another person

      And the following methods:

      • Write a constructor that sets the description of the characteristic to given String and sets the rating to zero to indicate that it has not yet been determined.
      • Write a private method isValid(aRating) that returns true if the given rating is valid, that is, it is between 1 and 10
      • Write a method setRating(aRating) that sets the rating to aRating if it is valid
      • Write a method setRating() that reads a rating from the keyboard. If the rating entered is not valid, keep asking the user until they enter one that is valid.
      • Implement get, and set methods for all attributes (except the setter for rating, which was done above).

      Implement this class in Java and write a main() method within it to test it.

      Name this program Characteristic
      Place both classes in the edu.cuny.lehman.cmp326 package.

    6. Problem Set 6a

      1. List Prices

        Write a program that asks the user for the number of items purchased, and then the prices of those items. The program should then print out each price and the total, formatted nicely. Here is a sample run of the program:

        Please enter the total number of prices: 5
        Please enter a price (<enter> to end):  2.34
        Please enter a price (<enter> to end): .99
        Please enter a price (<enter> to end): 100
        Please enter a price (<enter> to end): 81.05
        Please enter a price (<enter> to end): 90
        Please enter a price (<enter> to end):
        
        Your receipt:
                 2.34
                 0.99
               100.00
                81.05
                90.00
        ----------------
        Total: 274.38

        There are a few different ways to format numbers in Java, some of them similar to formatting in Python. See this tutorial.

        Name this class ListPrices
        Place the class in the edu.cuny.lehman.cmp326 package.

      2. Reverse Array

        Write a static method which takes an array of ints as its argument, and reverses the order of the elements in the array. That is, the first and last elements are switched, the second and second last elements are switched, etc. For example, this method should change the array [1, 2, 3, 4] to the array [4, 3, 2, 1].

        Write a driver file to test your method. It should call your method with at least three different inputs.

        Hint: When an array is passed into a method as a parameter, what is passed in is the reference to the location of that array in memory, not the array itself.

        Name this class ReverseArray

    7. Problem Set 6b

        Only do problem 1.
      1. Medal Count

        Consider the class Athlete, which is available here. Add a static method to the class which takes an array of Athletes as its argument, and returns the total number of medals won by all athletes stored in the array. Change the package of Athlete.java if needed.

        Write a driver file to test your method. It should call your method with at least three different inputs.

        Upload the modified class Athlete.java

    8. Problem Set 6c

      1. Symmetric matrix

        Write a static method which takes a 2-dimensional array of type int, which represents a matrix, as its argument, and returns true if the matrix is symmetric and false otherwise. A matrix is symmetric if the entry at row i and column j is the same as the entry at row j and column i for each i and j. The diagonal entries (i.e. entries with the same row and column) can be any number.

        Write a driver file to test your method. It should call your method with at least three different inputs.

        Name this class SymMatrix.

    9. Problem Set 7a

      1. Books and Textbooks

        Create a class called Book, which has the following variables:

        • title, which is a String representing the title of the book
        • author, which is a String representing the author of the book (assume each book only has one author)

        a) Write a constructor for the class Book that takes in as parameters Strings representing the title and author of the book. Test this method by creating three different instances of type Book.

        b) Write the method toString() for the class Book which prints out the title of the Book, followed by " by ", and then the author. If the title of the book is "Never Cry Wolf", and the author of the book is "Farley Mowat", then its toString() method would return the String "Never Cry Wolf by Farley Mowat". Test this method by printing out the information for the three instance of Book created in part (a).

        c) Create a subclass of Book called Textbook. This subclass should have one additional variable: subject, which is a String representing the subject of the textbook. Write the constructor for Textbook that takes in as its parameters Strings representing the title, author, and subject of the TextBook. Test this method by creating three different instances of type Textbook.

        d) Write a toString() method that returns a String containing information (title, author, subject) about a Textbook. You can decide how to format the String. Test this method by printing out the information for the three instance of TextBook created in part (a).

        e) Write a method which takes in an array of Books and returns an array of TextBooks that contains exactly those Books in the input array which are also TextBooks.

    10. Problem Set 7b

      1. To do list, part 1

        You are going to write two classes that will work together to represent a to-do list. This is the first part, and we will write the first class and test it.

        a) Create a class TodoItem that represents an item on a to do list. It should be able to store the following information in its instance variables:

        • the to-do list item (i.e. "buy milk", "work on asteroids project")
        • the due date (storing only the day and month is enough)
        • the priority of the item
        You need to decide the best way to represent and store the above information.

        b) Write getters and setters for your instance variables in TodoItem. The setters should only set the instance variables to valid values. If the value passed to the setter is not valid (for example, if the priority of an item is represented by a number between 1 and 5, and the number 6 is passed to the setter), then the setter should print an error message and the program should exit.

        c) Write a toString() method for TodoItem.

        d) Make TodoItem implement the Comparable\ interface. To do this, you will need to write the method compareTo, which should compare two TodoItems based on their due date and priority. You can decide exactly how the comparison is made (i.e. whether the due date or the priority is more important), but document the choice in your code.

        e) Write a driver to test the above code. To test the compareTo method, create three different arrays of TodoItems and sort them using Arrays.sort(...)

    11. Problem Set 8a

      1. To do list, part 2 This is a continuation of problem set 7b.

        a) Create a class TodoList which contains an ArrayList of TodoItems. This will represent the to-do list.

        b) Write a method for adding an item to the to-do list. It should take in parameters for the to-do list item, the priority, and the due date. The method should then use these parameters to create a new TodoItem and add it to your ArrayList.

        c) Write a method that sorts the items in your to do list using the compareTo method you wrote in TodoItem. Use the fact that ArrayList implements the List interface, and the Java class Collections has a method to sort classes implementing the List interface.

        d) Test the above methods with at least three test cases each.

    12. Problem Set 8b

      1. Manhattan paths

        You are in downtown Manhattan, and would like to walk a certain number of blocks east and south. Write a method using recursion that will calculate the total number of possible paths. For example, if you wanted to go 1 block east and 2 blocks south, you could walk either:

        • 1 block east, then 2 blocks south
        • 1 block south, then 1 block east, then 1 block south
        • 2 blocks south, then 1 block east
        for 3 possible paths. Your method should take in two parameters, representing the numbers of blocks east and south that you want to walk.

        For simplicity, assume that you never walk north or west, Broadway doesn't exist, and that there are an infinite number of blocks in both directions in downtown Manhattan (so you can pass in any positive integers as the arguments).

        Write code to test your method.

        Hint: If you going five block east and five blocks south, say, then the total number of paths is equal to the total number of paths to go five blocks east and four blocks south plus the total number of paths to go four blocks south and five blocks east.

      2. Shrinking strings

        Write a recursive method that takes in a String and returns a new String in which any consecutive characters that are the same have been replaced by only one of that same character. For example, if your method takes in the String "Hello", it should return the String "Helo". If it takes in the String "abbcccdddda", it should return the String "abcda".

        Write code to test your method.

    13. Problem Set 9a

      For this problem set, you need to create two classes to simulate a file system, and then write a method that will recursively search through the file system for a given file.

      The first class should be called File, and have one instance variable called filename, which is a String.

      The second class should be called Directory, and have two instance variables. The first is an array of File objects, and the second is an array of Directory objects. Note that either of the arrays can be empty.

      To simulate a file system with these classes, you will have a starting Directory. The Directory instances in the array represent sub-directories in the file system, and the File instances in the array represent files in that directory. Each of the sub-directories, might also contain files and sub-directories, etc.

      Write a recursive method that takes in a String, representing a filename, and a Directory, representing the starting directory. This method should return true if a File with that filename is contained somewhere (possibly in a sub-directory, sub-sub-directory, etc.) in the starting Directory.

    14. Problem Set 9b

      Write a program that asks the user for the name of a file and a letter. Count the number of times that the letter appears in the file and display it to the screen.
    15. Problem Set 10a

      1. To do list, part 3

        a) Modify your TodoList class so that it can read in a file each which each line represents a to do list item (you can decide on the format for the file), and initialize an instance of TodoList with the information in the file.

        b) Write a method that writes the TodoList instance to a file in the format you chose in part (a) above.

        c) Write a main method that asks the user for a to do list file, reads it into your program, sorts the to do list, and writes the sorted to do list to a file.

    16. Problem Set 10b

      1. Guessing game revisited

        Rewrite your Guessing Game program from Problem Set 3b to use Exceptions to handle invalid guesses. (You can also write a new version of the whole program.)

        Specifically, once the user enters a guess, you should throw an exception if the guess is out of range. i.e. if the user is told to guess a number between 1 and 100, but enters 1001, then the code should thrown an exception with a helpful error message. Your code should also throw an exception if the user input is invalid (i.e. they enter a word instead of a number).

        Your code should also catch the above Exceptions, show the user an error message, and ask the user to re-enter their guess.

        Hint: One way to do this is to write a helper method which asks the user for their guess, and either returns a valid guess or throws an Exception. You can then call this helper method from your main method, using a try-catch block to handle any Exceptions.

      2. To do list, Part 4

        Currently you are handling errors in your To do list program by printing an error mesage to the screen and exiting. Instead, have any method that catches an error in this fashion instead throw an Exception. Catch all Exceptions in your main method.