Week 9

Reading

Slides

Download Slides

Exercises

  • Exercise 3.1.5
  • Exercise 3.1.6
  • Exercise 3.1.26*
  • Exercise 3.2.1
  • Exercise 3.2.4
  • Exercise 3.2.8
  • Exercise 3.2.10
  • Exercise 3.2.11
  • Exercise 3.2.12

NOTE: Additional Exercise 9.1 is mandatory!

NOTE: Additional Exercise 9.6 is mandatory!

Additional Exercises

Exercise 9.1 (Mandatory): Write a class Person to represent a person. The class should have the following fields: String firstName, String lastName, int age, and Person spouse. The spouse field is initially null.

Add two constructors:

  • Person(String first, String last)
  • Person(String first, String last, int age)

Add getters and setters:

  • Add getters for all fields.
  • Add setters, but only for lastName and spouse.

Add a method void birthday() which increases the persons age by one year.

Add a method boolean marry(Person that) which marries this person to that person by updating the spouse fields and joining their last names. For example: If Nathan Cole and Emily Parker are married they become Nathan Cole-Parker and Emily Cole-Parker.

  • A person cannot be married until they are 18 years old.
  • A person cannot be married if they are already married.

The method should return true if the marriage is successful.

Add a toString method that returns a String of the form Lucky Luke, 23, unmarried.

Add a main method to test your implementation.

Exercise 9.2: Write a class Duration to represent a time interval. The class should have one field of type long that stores the duration in seconds.

Write two constructors:

  • Duration(int seconds)
  • Duration(int hours, int minutes, int seconds)

Write methods to access the duration in different time units:

  • double getSeconds()
  • double getMinutes()
  • double getHours()
  • double getDays()

Using the class, how many years is pi * 10^7 seconds?

Note: The methods must return doubles so that we can report a duration as e.g. 1.3 years.

Exercise 9.3: Write a class GradeBook to represent a student's grades. The class should have fields String studentName, double averageGrade, and int gradeCount.

Add a constructor:

  • GradeBook(String name) - starts with 0 grades and average 0.0

Add a mutator method:

  • void addGrade(double grade) - adds a new grade and updates the average

Add an accessor method:

  • double getAverage()

Hint: The new average is: (old_average × count + new_grade) / (count + 1)

Exercise 9.4: Write a class TrafficLightController to manage a traffic light.

Define an enum TrafficLight with values RED, YELLOW, and GREEN.

The TrafficLightController class should have one field:

  • TrafficLight currentLight - the current state of the light

Add a constructor:

  • TrafficLightController() - starts with RED light

Add a mutator method:

  • void next() - advances to the next light in sequence (RED → GREEN → YELLOW → RED)

Add a method:

  • String getInstruction() - returns "STOP" for RED, "GO" for GREEN, "PREPARE TO STOP" for YELLOW

Exercise 9.5: Write a class Book to represent a library book. The class should have fields String isbn, String title, String author, and boolean isCheckedOut.

Add a constructor:

  • Book(String isbn, String title, String author) - starts with isCheckedOut as false

Add methods:

  • boolean checkOut() - checks out the book if available, returns true on success
  • boolean returnBook() - returns the book if checked out, returns true on success
  • String toString() - returns a string like "The Great Gatsby by F. Scott Fitzgerald [Available]"

Write a class Library to manage a collection of books. The class should have fields Book[] books and int bookCount.

Add a constructor:

  • Library(int capacity) - creates an array with the given capacity

Add methods:

  • void addBook(Book book) - adds a book to the library
  • boolean checkOut(String isbn) - finds and checks out the book with the given ISBN
  • boolean returnBook(String isbn) - finds and returns the book with the given ISBN
  • Book[] getAvailableBooks() - returns an array of books that are not checked out

Exercise 9.6 (Mandatory): A student was asked to solve the following exercise:

Write a class ShoppingCart to represent a shopping cart in an online store. The class should store the cart owner's name, an array of item names, an array of item prices, and track how many items are in the cart. Include a constructor, methods to add items, remove items, calculate the total price, and apply a discount.

The student wrote the following code:

class cart {
    public String n; // name, maybe unused?
    protected double total; //total price of items
    public String[] items; // this is the items

    public void add(String item, double p) {
        items[count] = item; prices[count] = p; count++;
        total = total + p;
        return;
    }

    // count how many items are in the shopping cart
    int size;

    cart(String n, int size) {
        n = n;
        this.size = this.size;
        //initialise the fields of the class.
        items = new String[100];
        prices = new double[100];
        items = new String[100];
    }

    // Getter method
    public double getTotal() { return total; }

    // count how many items are in the shopping bag
    public static int count = 0; // counter variable
    private double[] prices; //stores the cost

    public void remove(String x) {
        for(int i=0;i<count;i++){
    if(items[i].equals(x)){
        total=total-prices[i];
                for(int j=i;j<count-1;j++){
            items[j]=items[j+1];
            prices[j]=prices[j+1];
        }
                 count--;
        return;
            }}
    }

    public String discount(   double persent) {
        if (persent > 0) {
            total = (double) ((double) total - ((double) total * (double) persent));
            } else {
                total = total - (total * persent);
        } return null; }}
  • What do you think of the code style?
  • Do you find the comments helpful?
  • Refactor the code such that it follows best practices.