Object-Oriented Programming with Java, part I + II

cc

This material is licensed under the Creative Commons BY-NC-SA license, which means that you can use it and distribute it freely so long as you do not erase the names of the original authors. If you make changes in the material and want to distribute this altered version of the material, you have to license it with a similar free license. The use of the material for commercial use is prohibited without a separate agreement.

Authors: Arto Hellas, Matti Luukkainen
Translators to English: Emilia Hjelm, Alex H. Virtanen, Matti Luukkainen, Virpi Sumu, Birunthan Mohanathas, Etiënne Goossens
Extra material added by: Etiënne Goossens, Maurice Snoeren, Johan Talboom
Adapted for Informatica by: Ruud Hermans

The course is maintained by Technische Informatica Breda


Exercise assignments-6-1: PhoneBook

In this assignment we are implementing a simple phone book.

Exercise assignments-6-1.1: Person

Start by programing the class Person which works as follows:

public static void main(String[] args) {
    Person pekka = new Person("Pekka Mikkola", "040-123123");

    System.out.println(pekka.getName());
    System.out.println(pekka.getNumber());

    System.out.println(pekka);
    pekka.changeNumber("050-333444");
    System.out.println(pekka);
}

The output is:

Pekka Mikkola
040-123123
Pekka Mikkola  number: 040-123123
Pekka Mikkola  number: 050-333444

So you have to implement the following class:

  • the method public String toString(), which returns the string representation formulated as the above example shows
  • constructor that sets the person name and phone number
  • public String getName(), that returns the name
  • public String getNumber(), that returns the phone number
  • the method public void changeNumber(String newNumber), that can be used to change the phone number of the person

Exercise assignments-6-1.2: Adding persons to Phonebook

Program the class Phonebook that stores Person-objects using an ArrayList. At this stage you’ll need the following methods:

  • public void add(String name, String number) creates a Person-object and adds it to the ArrayList inside the Phonebook
  • public void printAll(), prints all the persons inside the Phonebook

With the code:

public static void main(String[] args) {
    Phonebook phonebook = new Phonebook();

    phonebook.add("Pekka Mikkola", "040-123123");
    phonebook.add("Edsger Dijkstra", "045-456123");
    phonebook.add("Donald Knuth", "050-222333");

    phonebook.printAll();
}

the output should be:

Pekka Mikkola  number: 040-123123
Edsger Dijkstra  number: 045-456123
Donald Knuth  number: 050-222333

Exercise assignments-6-1.3: Searching for numbers from the phonebooks

Extend the class Phonebook with the method public String searchNumber(String name), that returns the phone number corresponding to the given name. If the sought person is not known the string “number not known” is returned.

Example code:

public static void main(String[] args) {
    Phonebook phonebook = new Phonebook();
    phonebook.add("Pekka Mikkola", "040-123123");
    phonebook.add("Edsger Dijkstra", "045-456123");
    phonebook.add("Donald Knuth", "050-222333");

    String number = phonebook.searchNumber("Pekka Mikkola");
    System.out.println( number );

    number = phonebook.searchNumber("Martti Tienari");
    System.out.println( number );
}

output:

040-123123
number not known

Exercise assignments-6-2: Money

In a previous assignment we stored the balance of a LyyraCard using a double variable. In reality money should not be represented as a double since the double arithmetics is not accurate. A better idea would be to implement a class that represents money. We’ll start with the following class skeleton:

public class Money {

    private final int euros;
    private final int cents;

    public Money(int euros, int cents) {

        if (cents > 99) {
            euros += cents / 100;
            cents %= 100;
        }

        this.euros = euros;
        this.cents = cents;
    }

    public int euros(){
        return euros;
    }

    public int cents(){
        return cents;
    }

    public String toString() {
        String zero = "";
        if (cents <= 10) {
            zero = "0";
        }

        return euros + "." + zero + cents + "e";
    }
}

Notice that the instance variables euros and cents have been defined as final meaning that once the variables have been set, the value of those can not be changed. An object value of which can not be changed is said to be immutable. If we need to e.g. calculate the sum of two money objects, we need to create a new money object that represents the sum of the originals.

In the following we’ll create three methods that are needed in operating with money.

Exercise assignments-6-2.1: Plus

Let us start by implementing the method public Money plus(Money added), that returns a new object Money that has a value equal to the sum of the object for which the method was called and the object given as parameter.

Examples of the method usage:

Money a = new Money(10,0);
Money b = new Money(5,0);

Money c = a.plus(b);

System.out.println(a);  // 10.00e
System.out.println(b);  // 5.00e
System.out.println(c);  // 15.00e

a = a.plus(c);          // NOTE: new Money-object is created and reference to that
                        //           is assigned to variable a.
                        //       The Money object 10.00e that variable a used to hold
                        //           is not referenced anymore

System.out.println(a);  // 25.00e
System.out.println(b);  // 5.00e
System.out.println(c);  // 15.00e

Exercise assignments-6-2.2: less

Create the method public boolean less(Money compared), that returns true if the object for which the method was called is less valuable than the object given as parameter.

Money a = new Money(10,0);
Money b = new Money(3,0);
Money c = new Money(5,0);

System.out.println(a.less(b));  // false
System.out.println(b.less(c));  // true

Exercise assignments-6-2.3: Minus

And finally create the method public Money minus(Money decremented), that returns a new object Money that has a value equal to the object for which the method was called minus the object given as parameter. If the value would be negative, the resulting Money object should have the value 0.

Examples of the method usage:

Money a = new Money(10,0);
Money b = new Money(3,50);

Money c = a.minus(b);

System.out.println(a);  // 10.00e
System.out.println(b);  // 3.50e
System.out.println(c);  // 6.50e

c = c.minus(a);         // NOTE: new Money-object is created and reference to that is assigned to variable c
                        //       the Money object 6.50e that variable c used to hold, is not referenced anymore

System.out.println(a);  // 10.00e
System.out.println(b);  // 3.50e
System.out.println(c);  // 0.00e

Exercise assignments-6-3: Grade distribution

This assignment corresponds to three assignment points.

Note: Your program should use only one Scanner object, i.e., it is allowed to call new Scanner only once. If you need scanner in multiple places, you can pass it as parameter:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    // ...

    doSomething(scanner);
}

public static void doSomething(Scanner scanner) {
    String riw = scanner.nextLine();
    // ...
}

If another object needs a scanner, you can pass it as constructor parameter and save in instance variable.

Note: Do not save anything in static variables. The main method is executed by the tests multiple times so the use of static variables might cause problems.

The input of the program is a set of exam scores of a course. Each score is an integer. When -1 is entered, the program stops asking for further input.

Inputting the exam scores should work as follows:

Type exam scores, -1 completes:
~~34
41
53
36
55
27
43
40
-1~~

After the scores have been read, the program prints the grade distribution and acceptance percentage of the course in the following form:

Grade distribution:
5: **
4:
3: ***
2: *
1: *
0: *
Acceptance percentage: 87.5

Grade distribution is formed as follows:

  • Each exam score is mapped to a grade using the same formula as in exercise 18. If the score is not within the range 0-60 it is not taken into account.
  • The number of grades are printed as stars, e.g. if there are 2 scores that correspond to grade 5, the line 5: ** is printed. If there are no scores that correspond to a particular grade, as is the case with grade 4 in the above example, the printed line is 4:

All the grades besides zeros are accepted, so in the above 7 out of 8 participants were accepted. Acceptance percentage is calculated with the formula 100*accepted/allScores.

Exercise assignments-6-4: Birdwatchers database

Note: Your program should use only one Scanner object, i.e., it is allowed to call new Scanner only once.

Note: Do not save anything in static variables. The main method is executed by the tests multiple times so the use of static variables might cause problems.

This assignment corresponds to three assignment points.

In this assignment you are supposed to design and implement an observation database for a bird watcher. The database contains birds, each of which have a name and a Latin name, both Strings. Database also tracks how many times each bird has been observed.

The program should implement the following commands:

  • Add - adds a bird
  • Observation - adds an observation
  • Statistics - prints all the birds
  • Show - prints one bird
  • Quit - terminates the program

The program should also handle the invalid inputs (see Turing below).

The following is an example how the program is supposed to work:

? ~~Add~~
Name: ~~Raven~~
Latin Name: ~~Corvus Corvus~~
? ~~Add~~
Name: ~~Seagull~~
Latin Name: ~~Dorkus Dorkus~~
? ~~Observation~~
What was observed:? ~~Seagull~~
? ~~Observation~~
What was observed:? ~~Turing~~
Is not a bird!
? ~~Observation~~
What was observed:? ~~Seagull~~
? ~~Statistics~~
Seagull (Dorkus Dorkus): 2 observations
Raven (Corvus Corvus): 0 observations
? ~~Show~~
What? ~~Seagull~~
Seagull (Dorkus Dorkus): 2 observations
? ~~Quit~~

Note you may structure your program freely, it is only required that the output of the program is as in the above example.