Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

All Exercises in This Part

Exercise 2.1: Clock 1 p.

Create a class called Clock with the integer attributes minutes and hours.

Add the methods setMinutes and setHours to the class. These methods take the minutes and hours to be set as parameters. The value of minutes must be between 0 and 59; otherwise, an error message should be printed and the time should remain unchanged. Similarly, the value of hours must be between 0 and 23; otherwise, an error message should be printed.

Also create a method called displayTime that prints the time in the format "HH:MM".

You can test the functionality of the class using the provided main program.

Complete this exercise in TIM
Exercise 2.2: Timer 1 p.

Create a class called Timer with the integer attributes minutes and seconds.

Add the methods addMinutes and addSeconds to the class. These methods take the number of minutes and seconds to be added to the timer as parameters. Also add a method called toString that returns the timer's minutes and seconds as a string.

The number of minutes can be any non-negative value, but the number of seconds must always be between 0 and 59. If the seconds exceed this range, they must be converted into minutes. You can convert seconds into minutes and remaining seconds as follows:

int seconds = 75; // Example of value in parameter

// This gives the amount of minutes to be added
int minutesToAdd = (this.seconds + seconds) / 60;

int remainingSeconds = (this.seconds + seconds) % 60;

You can test the functionality of the class using the provided main program.

Complete this exercise in TIM
Exercise 2.3: Own class 1 p.

Choose a real-world object or concept and create your own simple class for it.

Add the following to the class:

  • At least two attributes that are appropriate for the class.
  • At least two methods that modify or examine the state of the object in some way.
  • At least two different constructors that initialize the object to a sensible state.

What constitutes a sensible state depends on the object you choose. You may use the examples from the course material as inspiration when coming up with attributes and methods.

Create an object and experiment with changing its state in the main program. Print the object's information both before and after modifying its state.

Complete this exercise in TIM
Exercise 2.4: Static 1 p.

Modify the example Person class so that every created person is automatically assigned a unique identification number, which is an integer. The first person created should receive the number 1, the next person should receive the number 2, and so on.

The number must not be assigned from outside the object, for example by calling one of its methods.

Also implement a method called getNumber that returns the identification number of a particular object as an integer. No other methods need to be added.

Tip

You will need static class members in this exercise.

Before you begin, consider the following questions:

  • When does an object receive its number?
  • How does an object know what its number should be?
  • What information is shared among all objects, and what information is specific to each object?
Complete this exercise in TIM
Exercise 2.5: Phone 1 p.

Create a class called Phone with the attributes brand (a string) and batteryLevel (an integer representing the battery charge as a percentage between 0 and 100).

Add the following methods to the class:

  • sendMessage(String person, String message): prints a message in the format: "Sending a message to <person>: <message>" Sending a message reduces the battery level by 5 percentage points.

  • call(String person, int minutes): prints a message in the format: "Calling <person>, duration: <minutes> minutes" Making a call reduces the battery level by 1 percentage point per minute.

  • charge(int percentage): increases the battery level by the given amount, but the battery level cannot exceed 100%.

  • printInfo(): prints the phone's brand and battery level in the format: "The battery level of the <brand> phone is <battery>%."

Replace the parts enclosed in angle brackets with the appropriate attribute or parameter values.

The battery level cannot drop below 0%.

If the battery level is 0%, messages cannot be sent and calls cannot be made. Print: "Battery empty. Cannot send message." or "Battery empty. Cannot make a call."

Test your application by creating a Phone object, sending a message, making a call, charging the battery, and printing the phone's information.

Optional additional exercise: if battery runs out

Modify the sendMessage and call methods so that if the battery level is not sufficient to send the entire message or complete the entire call, the message is sent or the call is made only for as long as the battery lasts.

If the battery runs out during a message or call, print how much of the message was successfully sent or how long the call lasted before the battery was depleted. For example:

  • "Battery empty. You managed to send 60% of the message."
  • "The battery ran out after 3 minutes."
Complete this exercise in TIM
Exercise 2.6: Library 1 p.

Implement a class called Book that keeps track of individual books while also maintaining global library statistics. Create the following variables for the class:

Instance variables:

  • String title: The title of the book.
  • String author: The author of the book.
  • boolean isBorrowed: Indicates whether the book is currently on loan.

Class variables (static):

  • static int totalBooks: The total number of books that have been created.
  • static int borrowedBooks: The number of books that are currently on loan.

The constructor should take the title and author as parameters. Whenever a new book is created, the totalBooks variable should be increased by one.

Create the instance methods borrow() and returnBook(). These methods change the book's isBorrowed status and update the static borrowedBooks counter.

Create a static method printStatistics() that prints the library statistics in the following format: "Library contains X books, of which Y are currently on loan."

A main program is provided that you can use to test your implementation.

Complete this exercise in TIM
Exercise 2.7: Door 1 p.

Implement a class called Door that models a door which can be either locked or open.

Attributes:

  • private boolean locked
  • private String keyCode

The constructor receives the door's key code as a parameter: Door(String keyCode)

The constructor must set the key code and initially set the door to the locked state.

Methods:

  • boolean open(String code): opens the door only if the code is correct and the door is locked. Returns true if the door was opened; otherwise returns false.

  • boolean lock(): locks the door only if it is open. Returns true if locking was successful; otherwise returns false.

  • boolean changeCode(String oldCode, String newCode): changes the key code to a new one if the old code is correct and the door is open. The new code cannot be an empty string. Returns true if the change was successful; otherwise returns false.

  • String getStatus(): returns either "Door is locked" or "Door is open".

Only getStatus() may produce output. The other methods must not print anything.

Write a main program that:

  • creates a door
  • locks the door
  • attempts to open the door with an incorrect code
  • opens the door with the correct code
  • attempts to open an already open door
  • attempts to lock an already locked door
  • attempts to change the code while the door is locked
  • attempts to change the code using an incorrect old code
  • changes the code using the correct old code
  • prints the status of the door

Complete this exercise in TIM
Exercise 2.8: Piggy bank 1 p.

Implement a class called PiggyBank, whose purpose is to store money.

Attributes:

  • private double balance: The current amount of money in the piggy bank.
  • private String owner: The name of the piggy bank's owner.
  • private final String PASSWORD: A password required for withdrawing money.

Constructor:

  • Takes owner and PASSWORD as parameters.
  • Sets the initial balance to 0.0.

Methods:

  • public void deposit(double amount): Adds money only if amount is positive.
  • public double withdraw(double amount, String suppliedPassword): Checks whether suppliedPassword is correct. Checks whether there is enough money in the piggy bank. If both conditions are met, decreases the balance and returns the withdrawn amount. Otherwise, returns 0.0 and prints an error message.
  • public void printBalance(): Prints "Hello <owner>, the balance of your piggy bank is <balance> euros."

Replace the parts enclosed in angle brackets with the appropriate attribute or parameter values.

Create a main program in which you create a PiggyBank object and test its functionality in different situations, such as depositing money, a successful withdrawal, and unsuccessful withdrawals (incorrect password, withdrawal amount exceeding the available balance).

Complete this exercise in TIM
Exercise 2.9: Electric grid 1 p.

In this exercise, you will build a system that monitors the electricity consumption of buildings and prevents fuses from blowing. The exercise consists of several stages.

Stage 1: Electrical Device

Create a class called ElectricalDevice.

Devices have two immutable properties: a name and a current consumption in amperes.

Add the attributes:

  • private final String NAME
  • private final double CURRENT

Assume that the current consumption is always a positive number.

Create a constructor that initializes these values.

Add private boolean connected, which indicates whether the device is turned on.

Implement the methods connect() and disconnect(), which modify the state of the connected variable. Also implement a getCurrent() method that returns the device's current consumption, and a corresponding getName() method.

Test your class in a main program by creating a few devices and turning them on and off.

Stage 2: Electrical Panel and Object List

Create a class called ElectricalPanel. The purpose of this class is to manage electrical devices.

Add the attribute final double FUSE_RATING. A fuse rating might be, for example, 16 amperes or 35 amperes.

Also add private boolean fuseActive, which indicates whether the fuse is intact (true) or blown (false). Initially, the fuse is active.

Create List<ElectricalDevice> connectedDevices (use an ArrayList).

Implement the method double calculateCurrentConsumption(), which iterates through the list and calculates the sum of the devices' CURRENT values.

Stage 3: Supervisory Logic and State Management

The panel must decide whether a device can be turned on.

Implement the method boolean connect(ElectricalDevice device). The method should check whether the current consumption plus the new device's current consumption is less than or equal to the fuse rating. If so, the device is added to the list and device.connect() is called. Otherwise, the fuse blows: set fuseActive = false, turn off all devices in the list by calling disconnect(), and clear the list of connected devices.

Also implement the method void disconnect(ElectricalDevice device), which removes the device from the list and calls device.disconnect().

Stage 4: Global Monitoring

The power company wants to monitor the status of all electrical panels.

Add static double totalNationalConsumption to the ElectricalPanel class.

Update this variable whenever any device in any panel is turned on, disconnected from a panel, or when a fuse blows.

Add a static method printNationalStatus(), which prints the total electricity consumption.

You can test your program using the provided main program in TIM, or you may write your own test program.

Complete this exercise in TIM
Exercise 2.10: Reservations 1 p.

Modify the example program containing the Building, Room, and Reservation classes so that the program does not allow overlapping reservations to be added to the same room. If the room already has a reservation that overlaps with a new reservation, the new reservation must not be created.

Also add validation checks that prevent invalid reservations from being created. The reservation duration must be at least 1 hour, and the start time must be between 0 and 23.

In this exercise, error situations may be handled by printing an error message.

Before starting the exercise, it is worth taking a moment to consider which responsibilities belong to which objects.

You can test your program using the provided main program.

Complete this exercise in TIM