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

  • Problem Set 1

    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. If you don't know Python, think of the following code as pseudo code.

      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

    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.

      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

  • Problem Set 2

    1. Days to Weeks

      Write a program that asks the user for the number of days, and then prints out how many weeks (and days) that is.

      For example, if the user entered 10, your program would output 1 weeks 3 days. If the user entered 25, your program would output 3 weeks 4 days. Note that you can use "weeks" and "days" for all inputs, even when it is grammatically incorrect.

      Name this class DayConverter

    2. Cooking Converter

      Write a program that converts a recipe measurement in teaspoons (tsp.) and tablespoons (tbsp.) into milliliters (mL). Your code shoud ask the user for the number of teaspoons and tablespoons, and then print the total number of millilters in both. 1 tsp. = 4.9289 mL and 1 tbsp. = 14.7868 mL

      For example, if the user enters 2 tsp. and 1 tbsp., then your program should print out 24.6446mL ( = 2*4.9289mL + 14.7868mL).

      Name this class BakingConverter

  • Problem Set 3

    1. User ID

      Write a program that asks the user to enter their first and last name, separated by a space. This program then outputs a user ID, which is the first two letter of their first name, followed by the first four letters of their last name, followed by the number of characters in their full first and last name (but not counting the space). All letters in the user ID should be lower case.

      You may assume that the first name is at least two letters long, and that the last name is at least 4 letters long.

      For example, if the user entered "Jane Smith", then the user ID would be "jasmit9". If the user entered "Jose Rodriguez", then the user ID would be "jorodr13".

      Name this class UserID

    2. Train Fare

      Write a program that asks the user for the zone and the ticket type, and displays the train fare.

      • If the zone is 2 or smaller and the ticket type is "adult," the fare is 3.
      • If the zone is 2 or smaller and the ticket type is "child," the fare is 1.50.
      • If the zone is 3 and the ticket type is "adult," the fare is 4.
      • If the zone is 3 or 4 and the ticket type is "child," the fare is 3.
      • If the zone is 4 and the ticket type is "adult," the fare is 6.
      • If the zone is greater than 4 or less than 1, or if the ticket type is neither "adult" not "child", then display an error message.

      Name this class TrainFare

  • Problem Set 4

    1. Sports Stats

      Write a program that asks the user whether a team won or lost each of 10 games of some sport. The program then displays the number of games won, the number of games lost, the percentage of games won, and the percentage of games lost.

      The user can use 'w' to indicate a win and 'l' to indicate a loss. For example, if the user enters:

      				Game 1: w
      				Game 2: l
      				Game 3: l
      				Game 4: w
      				Game 5: l
      				Game 6: w
      				Game 7: l
      				Game 8: l
      				

      Then your code should display something like:

      				Number of wins: 3
      				Number of losses: 5
      				Percentage of games won: 37.5
      				Percentage of games lost: 62.5
      			

      If the user doesn't enter w or l, you can either ignore that game, or keep asking the user until they enter w or l.

      Name this class SportsStats

    2. Guessing game

      Write a guessing game program that asks the user to guess a secret number. If the guess is too high or too low, the program should display a message saying so and ask the user to guess again. If the user guesses correctly, your program should congratulate them and end.

      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

      Extra challenge: Instead of always having the program exit when the user guesses the number, ask the user if they want to play again (and let them do so, if they say yes).

      Extra hard challenge: Make your program cheat. That is, allow the program to change the secret number, so that it never contradicts the hints it has given before, but makes it take as long as possible for the player to win.

  • Problem Set 5


    1. Capitalize

      Write a method that takes in a String, and returns that same String, but with all the consonants in lower case and all the vowels in upper case.

      For example, the String "apple" would be returned as "ApplE", the String "a frog" would be returns as "A frOg", and the String "Toronto" would be returned as "tOrOntO".

      Call this method with at least three different inputs in the main method to test it.

      Hint: We wrote a method to check if a character is a vowel in our Pig Latin translation program.

      Name this class Capitalize

    2. Fibonacci numbers

      The Fibonacci numbers are the numbers in the sequence 1,1,2,3,5,8,13,21,... The sequence starts off with two 1s, and then each following number is the sum of the two numbers before it in the sequence. i.e. 2 = 1 + 1, 3 = 2+1, 5 = 3+ 2, etc.

      Write a method that takes in a integer n, and uses a loop to print out the first n Fibonacci numbers if n is 0 or positive. The method should print out an error message if n is negative. The method should not return anything.

      For example, if you pass 2 into the method, it should print "1,1". If you pass 5 into the method, it should print "1,1,2,3,5".

      Call this method with at least three different inputs in the main method to test it.

      Name this class Fibonnacci.

      Extra challenge: Add another parameter to your method, so that it either prints out the first n Fibonacci numbers or it prints out only the n-th Fibonacci number.

  • Problem Set 6


    1. Pig Latin

      Modify the Pig Latin program that we started writing in class to be able to translate all words into Pig Latin, not just those beginning with a vowel or a single consonant. You can either use the code you wrote in class, or down mine: code from class

      Recall that you translate an English word into Pig Latin using these rules:

      1) If the English word starts with one or more consonants, all consonants before the first vowel are removed from the front of the English word, and added to the end of it, keeping the order the same. The string “ay” is then added to the end of this string.

      2) If the English word starts with a vowel, append the string “hay” to the end of that word.

      Treat ‘y’ as a consonant.

      For example, good becomes oodgay, egg becomes egghay, and school becomes oolschay.

      Name this class PigLatin

      Extra challenge 1: Change the rules for how you treat y. Treat it as a consonant if it is at the beginning of a word, and as a vowel if it is in the middle of a word.

      Extra challenge 2: Ask the user for a sentence, and translate the whole sentence.

    2. Numbers

      Write a program that displays the numbers from 1 to n in a grid of a certain size. You should ask the user for n, as well as the number of columns for the grid. For example, if the user tells you n=15, columns = 3, your program should display something like
      1 2 3
      4 5 6
      7 8 9
      10 11 12
      13 14 15
      If the user tells you n = 10, columns = 3, your program should display something like
      1 2 3
      4 5 6
      7 8 9
      10

      Name this class Numbers

      Extra challenge: To format the grid nicely, look at the printf() method here.
  • Problem Set 7


    1. Person

      Write a class Person that contains 3 instances variables:

      • name, a String holding the name of the person
      • mother, a variable of type Person that represents the person's mother
      • father, a variable of type Person that represents the person's father

      Write the following methods for your class:

      • a constructor that takes in the name of the person
      • a toString() method that displays the name of the person, and the names of their mother and father, if available
      • a method that prints out the person's mother, father, and grandparents (if known)

      Test these methods in your main class by calling them at least three times.

      Hint: if you haven't initialized the mother and father instance variables, then they will have the value null. So you could test if the mother of Person bart is known (that is, initialized), by testing if (bart.mother != null) { //then the mother variable has been initialized, and can be access as bart.mother }

  • Problem Set 8


    1. Baseball Player

      Write a class BaseballPlayer that represents a baseball player. It should contain 4 private instances variables:

      • name, a String holding the name of the player
      • team, a String holding the team the player plays on
      • numRuns, a variable of type int that represents the total number of runs scored by the player
      • numOuts, a variable of type int that represents the total number of times the player has been out

      Write the following methods for your class:

      • a constructor that takes in the name of the player and his/her team
      • getters and setters for numRuns and numOuts. The setters should only allow these variables to be set to positive numbers, and should instead print an error message for any negative numbers (You can decide how to handle 0.)
      • a method that computes and returns the player's batting average, which is the total number of runs scored divided by the total number of outs
      • a toString() method that displays the name of the player, their team, and their batting average (call your method)
      • a method that prints out the person's mother, father, and grandparents (if known)

      Test all of these methods in your main class by calling them at least three times.

  • Problem Set 9


    1. Todo List Item

      Write a class TodoItem that represents an item in a to-do list. It should have the following private instance variables:

      • a String that holds a description of the item that needs to be done (ex. "walk dog")
      • an int that holds the month (converted to a number) that the item is due
      • an int that holds the day that the item is due
      • a boolean variable isDone that holds whether or not the item has been completed.

      The class should also have the following private static class variables, both initialized to 0:

      • an int numItems that holds how many TodoItem instances have been made
      • an int numDone that holds how many TodoItem instances have been completed

      Write the following methods for your class:

      • a constructor that takes in the description of the to-do item, the day it is due, and the month it is due (as an int). This constructor should initialize the boolean variable isDone to false. This constructor should also increment the class variable numItems.
      • a second constructor that only takes in the description of the to-do item. This constructor should initialize the boolean variable isDone to false. This constructor should also increment the class variable numItems.
      • a toString() method
      • getters and setters for the due day and month. The setters should only allow the due date to be set to a number between 1 and 31, and the due month to be set to a number between 1 and 12. (You can ignore that fact that some months have less than 31 days.)
      • a non-static method that checks off an item as being done. Specifically, it should set the instance variable isDone to true, and increment the class variable numDone.
      • a static method that returns the percentage of to-do list items completed. (That is, it shoud return numDone/numItems as a double).

      Test all of these methods (except the getters) by calling them at least three times in your main method.

  • Problem Set 10


    1. Fighting Monster Game

      Goal: Write a class and use it in a program. Review of loops.

      For this problem set, you will write a class GameCharacter that represents a character, either good or bad, in a video game. You will then use this class to write a simple game in which the player fights a monster. Both the player and the monster will be represented as instances of GameCharacter.

      Create a class GameCharacter that contains 3 private instances variables:

      • name, a String holding the name of the character
      • health, an int holding a number representing how healthy the character is
      • isDefending, a boolean variable representing whether or not the character is in a defensive position

      Write the following methods for your class:

      • a constructor that takes in the name and health of the character
      • a non-static method attack that has the header public void attack(GameCharacter opponent). This method simulates an attack by this instance of GameCharacter on the opponent instance that was passed in as a parameter. If isDefending is true for opponent, then this method should print a message that they succesfully defended against the attack. If isDefending is false for opponent, then this method should print a message that the attack was successful, and decrease health of opponent by 2. Finally set isDefending to false for this instance (since they are no longer defending, but attacking).
      • a non-static method defend that sets the instance variable isDefending to true
      • a toString() method that displays the name and health of the character

      Write a static method test() in GameCharacter that calls each of the above methods at least three times to test them. Call test() at the beginning of the main() method to test your code. Make sure that your code is working before continuing.

      Once your code in GameCharacter is working, comment out the call to test().

      In the main() method of GameCharacter, write a program in which the user's character fights a monster. The code should start by asking the player for the name of his/her character, saying that the monster is attacking, and then at each turn, ask the user if they are attacking or defending. The monster always attacks. The fight should continue until either the player or the monster is unconscious/dead (has health <=0). Both the player and monster should be represented in the code as instances of GameCharacter.

      Here are more specific instructions:

      • ask the user for the name of their player
      • make two GameCharacter instances, one for the player (using their name) and one for a monster. You can set the player's health to 20 and the monster's to 15 (or whatever values you want)
      • write a while loop, that loops until either the monster or player is unconscious/dead, which corresponds to health <=0
      • in the while loop, ask the user whether they want to have their player attack or defend against the monster. Then call the corresponding method to simulate this
      • in the while loop, after the player has made their move, have the monster attack the player, by calling the appropriate method.
      • after the while loop is finish, print out who has won.

      Extra challenge: Make this game more interesting by using random numbers (http://docs.oracle.com/javase/8/docs/api/java/util/Random.html) for the initial health of the characters, and for the damage done during attacks.

  • Problem Set 11


    1. Equals method for BaseballPlayer

      Add a (non-static) equals(..) method to your class BaseballPlayer from Problem Set 8. This method should take in a single BaseballPlayer instance as a parameter, and return true if the name and team are the same as in the calling instance.

      Instead of your version, you can use the BaseballPlayer class I posted as the solution instead, but should say so in the comments.

    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].

      Test your method by calling it in the main(..) method with at least three different input arrays.

      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

  • Problem Set 12

    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.

      Test your method by calling it in the main(..) method with at least three different input arrays.

      Upload the modified class Athlete.java

    2. 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.

      Test your method by calling it in the main(..) method with at least three different input arrays.

      Name this class SymMatrix.

  • Name this class SymMatrix.

  • Problem Set 13

    1. To Do List, part 2

      Write a class TodoList that represents a to-do list. It will use the TodoItem class from previous homework. You can either use your version of this class, or download and use the version posted as a solution.

      The TodoList class should contain two instance variables:

      • an array of 100 TodoItem instances, that represents the to-do list.
      • an int numItems that holds the number of TodoItem instances that are actually in the array (the remaining slots will be unitialized or null). This variable should be initialized to 0, since the to-do list is empty.

      Since we must give an array a size when we initialize it, we (arbitrarily) set the size of the array representing the to-do list to be 100. That is, we can have up to 100 items in our to-do list. Many to-do lists have less than 100 items in them, so we have another variable that keeps track of exactly how many TodoItem instances are in the array. We will assume that the first numItems elements of the array are TodoItem instances, and the remaining elements are null.

      Write three methods for this class:

      • add: This method should take in a TodoItem as a parameter, and add it to the TodoItem array in the first empty slot. Instance variable numItems should be updated accordingly. If the array is already full of TodoItem instances, this method should print a message saying so, and do nothing.
      • delete: This method should take in an int, and return the TodoItem at that index in the TodoItem array. If there is no TodoItem instance at that index, this method should return null (what is currently in the array at that index, in this case). Addtionally, all TodoItem instances in the array at higher indices should be moved one position lower to delete this TodoItem from the array. Ex. If we delete the TodoItem instance at position 5, we would save it to be returned at the end of the method, and then move the TodoItem in position 6 into position 5, and then the TodoItem in position 7 into position 6, etc. Finally, update the instance variable numItems.
      • toString: This method should display the TodoItem instances in the array as a to-do list.

      Test these methods by calling them each at least three times.

  • Problem Set 14

    1. Player and Monster

      For this homework, you will create two subclasses of your class GameCharacter in homework 10. You can either use your version of GameCharacter, or you can download the one posted as the solution. The instructions below are the minimal requirements, but feel free to make a more elaborate game.

      The first subclass will represent the player's character. You can call this subclass Player, or you can call it a specific type of player character, like Fighter or Wizard. I will call it Player below.

      Create this subclass, and write the following methods:

      • a constructor which takes in a String representing the name of the Player. This constructor should set the health to either a specific value, like 20, or to a randomly chosen value from some range (say 20-25)
      • a method specialAttack(GameCharacter opponent), which simulates the Player making a special attack on the opponent. It should somehow be different than the attack(..) method in GameCharacter. For example, maybe it does 10 health points of damage, but only succeeds half the time the Player tries it. You can call this method something other that specialAttack if you prefer (i.e. castSpell, etc.)

      As in the GameCharacter homework, test these methods by writing a method test2 in GameCharacter that calls them each at least three times. Call test2 in the main method in GameCharacter to perform the tests (and then comment it out).

      Next create a subclass of GameCharacter called Monster (or a specific kind of villan like Ogre or Alien).

      For this subclass, write the following methods:

      • a (default) constructor which does not take in any parameters. It should set the name and health of the monster to something appropriate. (Again, you can randomly chose the health value from some range).
      • a method attack(GameCharacter opponent), which overrides the attack method in GameCharacter. You should make this method different from the default attack method in GameCharacter. For example, maybe the monster does 5 health points of damage, or maybe the monster succeeds with the attack 25% of the time when the Player is defending.
      • a method specialAttack(GameCharacter opponent) (or other appropriate name), which simulates the Monster making a special attack on its opponent. It should be different than the attack method you just defined.

      Again, test these methods by calling them at least three times in the method test2.

      Finally, modify the main method of GameCharacter so that the player is an instance of the Player class, and the monster is an instance of the Monster class. The player should now have the choice of attacking, performing the special attack, or defending each round. The monster should randomly chose between attack and specialAttack each round.

      Submit your GameCharacter, Player, and Monster class.

  • Problem Set 15

      Goal: Practice implementing the Comparable interface and overriding the equals(Object obj) method.

    1. Movies

      Create a class called Movie, which represents a movie, and which has the following variables:

      • title, which is a String representing the title of the movie
      • studio, which is a String representing the studio that made the movie

      a) Write a constructor for the class Movie that takes in as parameters Strings representing the title and studio of the movie.

      b) Write a toString() method for the class Movie, which returns a String with the title and studio, nicely formatted.

      c) Implement the Comparable interface for the class Movie. The method CompareTo should be written so that an array of Movies will be sorted first by studio, and then by title.

      Test your CompareTo method by creating three different arrays of Movie instances, and sorting them (use Arrays.sort(...)).

      d) Override the default equals(Object obj) method, so that two instances of a Movie are considered equal if they have the same studio and if their titles are the same (ignoring case). For example, movie instances with the titles "Lion King" and "Lion king" should be considered equal, if their studio is the same.

      Test your equals method by calling it on three different test cases. Additionally, if you create two arrays of Movie instances, you can now compare them by calling Arrays.equals(..), which will call your equals method to test the pairs of instances.

  • Problem Set 16

    1. To do list, part 3

      This is a continuation of problem sets 9 and 13. You may either use your own TodoItem and TodoList classes, or the ones posted as solutions (or a combination of the two).

      a) Make TodoItem implement the Comparable<TodoItem> interface. To do this, you will need to write the method compareTo, which should compare two TodoItems based on their due date (you can assume all items have the same year).

      Test your compareTo method by calling it three times in the main() method.

      b) Write a method sort in TodoList that takes in no parameters and sorts the items in your to-do list (the TodoItem array). You can use Arrays.sort(...), which will use the compareTo method you wrote in part a.

      Test this method on three different to-do lists.

    2. Recursive mystery function

      In a new class, implement the following psuedocode method mystery. Call it several times from the main() method to see what it does.

           	function mystery(num) {
      if num <= 0 then return 1 return 3*mystery(num -1) }
  • Problem Set 17

    1. Recursion mystery function

      In a new class, implement the following psuedocode method mystery. Call it several times from the main() method to see what it does.

           	function mystery( num ) {
           		if num<2 {
               		print num
               		return
           		}
           		mystery(num/2)
           		print num % 2
           	}
           	

      Note: For this mystery function, print should not add a newline at the end.

    2. 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.

  • Problem Set 18

    1. 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".

      Test your method.

    2. Searching the family tree

      For this problem, you will use the Person class you wrote for problem set 7. You can either use your own version or the one posted as the solution. Recall that a Person has a name, and a mother and a father, which will also be Person instances, if they are known.

      Write a non-static recursive method findAncestor that takes in a String, representing a name. This method should return true if the calling instance (this) or any of the calling instance's known ancestors have that name, and false otherwise.

      For example, if you look at the Person class posted as the solution for problem set 7, you will see that it makes instances for Bart, Marge, Homer, and Grampa Simpson. For these instances, calling bart.findAncester("Grampa Simpson") should return true, while calling bart.findAncester("Lisa") should return false. Note that the family tree could go back many generations, so you will have to use recursion to search it.

      Test your method by calling it at least three times.

  • Problem Set 19

    1. Shrinking strings

      Write a recursive method that takes in an number n and prints out n stars (*). For example, if your method takes in the number 5, it should print out *****.

      Test your method.

    2. File Search

      The two classes File.java and Directory.java represent a file and a directory, respectively, in a simulated file system.

      The File class has one instance variable, a String called name, which holds the name of the file.

      The Directory class has 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 null (empty). The File and Directory instances in these arrays represent the contents of this Directory (i.e. the files and directories that it contains).

      Look at the test case in the main method of Directory. This simulates a file system with the base directory "Dir 6". "Dir 6" contains the file "File 9" and the sub-directories "Dir 4" and "Dir 5". Directory "Dir 5" contains no files and no directories. Directory "Dir 4" contains files "File 7" and "File 8" and directory "Dir 3". So "Dir 6" contains file "File 8" two levels down, etc.

      Complete the recursive method containsFile(..) in Directory. This method takes in a String representing a filename, and returns true if a File with that filename is contained somewhere (possibly in a sub-directory, sub-sub-directory, etc.) in the calling Directory.

      Hint: it might help with debugging to write a toString method for each class.

  • Problem Set 20

    1. Letter count

      Write a program that asks the user for the name of a input file, an output file, and a letter. Write each line of the input file to the output file, followed by the number of times that the letter appears in that line.

      Name this class LetterCount

    2. To do list, part 4

      This problem continues problem sets 9, 13, and 16. You may either use your own TodoItem and TodoList classes, or the ones posted as solutions (or a combination of the two).

      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 instantiate an instance of TodoList with the information in the file. That is, for each line in the file, you should make a new TodoItem in the array in TodoList.

      b) Write a method that writes the TodoList instance to a file in the format you chose in part (a) above. (Hint: change your toString() method if necessary, to make things easier)

      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.

  • Problem Set 21

    1. Guessing game revisited

      Rewrite your Guessing Game program from Problem Set 4 to use Exceptions to handle invalid guesses i.e. if they enter a word instead of a number. (You can also write a new version of the whole program.)

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

  • -->