Problems

  1. Books and Textbooks (30 points)

    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) Implement the Comparable interface for the class Book. The method CompareTo should be written so that an array of Books will be sorted first by author, and then by title. Test this method by creating three different arrays of Books, and sorting them (use Arrays.sort(...)).

    d) 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.

    e) 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).

  2. Recursion 1 (10 points)

    Using recursion, write a method that computes the sum of the digits in a positive number. i.e. if the number is 14, the method returns 1+4 = 5, aor if the number is 239, the method returns 2+ 3+ 9 = 14

  3. Recursion 2 (10 points)

    Using recursion, write a method that takes in a String s and returns the reverse of that string. For example, if the input to the method is the String "Hello!", then the method would return the String "!olleH". If the input to the method is the String "a", then the method would return the String "a".

Submitting Your Problem Set

You should submit all problems for grading by the deadline (see class schedule for date). To submit a program, you need to demonstrate (during office hours or lab) your program and explain how it works.