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


Introduction to loops

Conditional statements allow us to execute different commands based on the conditions. For example, we can let the user login only if the username and password are correct.

In addition to conditions we also need repetitions. We may, for example, need to keep asking the user to input a username and password until a valid pair is entered.

The most simple repetition is an infinite loop. The following code will print out the string I can program! forever or “an infinite number of times”:

while (true) {
    System.out.println("I can program!");
}

In the example above, the while (true) command causes the associated block (i.e. the code between the curly braces {}) to be looped (or repeated) infinitely.

We generally do not want an infinite loop. The loop can be interrupted by changing the condition in the while-loop

boolean running = true;
while (running) {
    System.out.println("I can program!");

    System.out.print("Continue? ('no' to quit)? ");
    String command = reader.nextLine();
    if (command.equals("no")) {
        running = false;
    }
}

System.out.println("Thank you and see you later!");

Now the loop progresses like this: First, the program prints I can program!. Then, the program will ask the user if it should continue. If the user types no, the variable running is set to false, and the loop stops and Thank you and see you again! is printed. Take note that the commands in the loop will continue to execute, and the loop will stop at the end of the code block in the loop. As there is no other code in the loop, it stops immediately

I can program!
Continue? ('no' to quit)? ~~yeah~~
I can program!
Continue? ('no' to quit)? ~~jawohl~~
I can program!
Continue? ('no' to quit)? ~~no~~
Thank you and see you again!

Many different things can be done inside a loop. Next we create a simple calculator, which performs calculations based on commands that the user enters. If the command is quit, the variable running will be set to false, and the program will quit. Otherwise two numbers are asked. Then, if the initial command was sum, the program calculates and prints the sum of the two numbers. If the command was difference, the program calculates and prints the difference of the two numbers. If the command was something else, the program reports that the command was unknown.

System.out.println("welcome to the calculator");
boolean running = true;
while (running) {
    System.out.print("Enter a command (sum, difference, quit): ");
    String command = reader.nextLine();
    if (command.equals("quit")) {
        running = false;
    } else {
        System.out.print("enter the numbers");
        int first = Integer.parseInt(reader.nextLine());
        int second = Integer.parseInt(reader.nextLine());

        if (command.equals("sum") ) {
            int sum = first + second;
            System.out.println( "The sum of the numbers is " + sum );
        } else if (command.equals("difference")) {
            int difference = first - second;
            System.out.println("The difference of the numbers is " + difference);
        } else {
            System.out.println("Unknown command");
        }
    }
}

System.out.println("Thanks, bye!");

Note that this code uses the reader to read user input. To make this reader object, don’t forget to add the following line to your code:

Scanner reader = new Scanner(System.in);

Exercise while-loop-1 : Password

In this exercise we create a program that asks the user for a password. If the password is right, a secret message is shown to the user.

Type the password: ~~turnip~~
Wrong!
Type the password: ~~beetroot~~
Wrong!
Type the password: ~~carrot~~
Right!

The secret is: jryy qbar!

The program will be done in three steps.

Exercise while-loop-1.1: Asking for the password

The initial exercise template defines the variable String password with a value of carrot. Do not change this password! You should make the program ask the user to enter a password and then compare it with the value in the variable password. Remember what that there is a special way to compare strings!

Type the password: ~~turnip~~
Wrong!
Type the password: ~~carrot~~
Right!
Type the password: ~~potato~~
Wrong!

Exercise while-loop-1.2: Asking for the password until the user gives the correct one

Modify the program so that it asks the user to type a password until it gets the correct one. Implement this using a while-true loop statement. The loop statement can be interrupted if and only if the entered password matches the value of the password variable.

Type the password: ~~turnip~~
Wrong!
Type the password: ~~beetroot~~
Wrong!
Type the password: ~~carrot~~
Right!

Exercise while-loop-1.3: Secret message

Add your own secret message to the program and show it to the user when the password is correct. Your message can be whatever you want!

Type the password: ~~turnip~~
Wrong!
Type the password: ~~beetroot~~
Wrong!
Type the password: ~~carrot~~
Right!

The secret is: jryy qbar!

The secret above has been encrypted using the Rot13 algorithm. During this course we will implement our own encryption program.

Exercise while-loop-2 : Temperatures

You will get the Graph component along with the exercise template. Graph draws graphs based on numbers that are given to it. You can give it numbers as follows:

Graph.addNumber(13.0);

We will create a program that draws a graph based on daily temperatures given to it.

Exercise while-loop-2.1: Asking for numbers

Create a program that asks the user to input floating point numbers (double) and then adds the numbers to the graph. Use the while-true structure again.

Note: To read a double, use: double number = Double.parseDouble(reader.nextLine());

Exercise while-loop-2.2: Checking

Improve your program so that temperatures below -30 degrees or over +40 degrees are ignored and not added to the graph.

Exercise while-loop-3 : NHL statistics, part 2

We will continue using the NHL component introduced earlier and create a program that the user can use to query for statistics.

The program is structured similarly to the Calculator example program above. The program body is as follows:

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

   System.out.println("NHL statistics service");
   boolean running = true;
   while (running) {
       System.out.println("");
       System.out.print("command (points, goals, assists, penalties, player, club, quit): ");
       String command = reader.nextLine();

       if (command.equals("quit")) {
           running = false;
       } else if (command.equals("points")) {
           // print the top ten playes sorted by points
       } else if (command.equals("goals")) {
           // print the top ten players sorted by goals
       } else if (command.equals("assists")) {
           // print the top ten players sorted by assists
       } else if (command.equals("penalties")) {
           // print the top ten players sorted by penalties
       } else if (command.equals("player")) {
           // ask the user for the player name and print the statistics for that player
       } else if (command.equals("club")) {
           // ask the user for the club abbreviation and print the statistics for the club
           // note: the statistics should be sorted by points
           //     (players with the most points are first)
       }
   }
}

The program asks the user to give commands and then executes the operation that is associated with the given command. The commands are: points, goals, assists, penalties, player, club, quit.

You should write code in the parts marked with comments.

Here is an example demonstrating the program in action:

NHL statistics service

command (points, goals, assists, penalties, player, club): ~~assists~~
Henrik Sedin           VAN        43 11 + 38= 49  36
Erik Karlsson          OTT        43  6 + 35= 41  24
Claude Giroux          PHI        36 18 + 30= 48  16
Pavel Datsyuk          DET        41 13 + 30= 43  10
Brian Campbell         FLA        42  3 + 30= 33   4
Daniel Sedin           VAN        42 18 + 29= 47  32
Jason Pominville       BUF        41 14 + 29= 43   8
Nicklas Backstrom      WSH        38 13 + 29= 42  22
Joffrey Lupul          TOR        41 19 + 28= 47  36
Evgeni Malkin          PIT        33 16 + 28= 44  30

command (points, goals, assists, penalties, player, club): ~~player~~
which player: Jokinen
Olli Jokinen           CGY        43 12 + 21= 33  32
Jussi Jokinen          CAR        40  4 + 19= 23  30

command (points, goals, assists, penalties, player, club): ~~club~~
which club: DET
Pavel Datsyuk          DET        41 13 + 30= 43  10
Johan Franzen          DET        41 16 + 20= 36  34
Valtteri Filppula      DET        40 14 + 21= 35  10
Henrik Zetterberg      DET        41  8 + 24= 32  14
// and more players

command (points, goals, assists, penalties, player, club): ~~quit~~

Note: When you first run the program, the execution might take a while because the information is downloaded from the internet. Execution should be quick after the first run.

Exercise while-loop-4 : Sum of many numbers

Create a program that reads numbers from the user and prints their sum. The program should stop asking for numbers when user enters the number 0. The program should be structured like this:

Scanner reader = new Scanner(System.in);
int sum = 0;
boolean running = true;
while (running) {
   int read = Integer.parseInt(reader.nextLine());
   if (read == 0) {
       running = false;
   } else {

   // DO SOMETHING HERE

     System.out.println("Sum now: " + sum);
   }
}

System.out.println("Sum in the end: " + sum);
~~3~~
Sum now: 3
~~2~~
Sum now: 5
~~1~~
Sum now: 6
~~1~~
Sum now: 7
~~0~~
Sum in the end: 7

while conditions

The running variable is not the only way to end a loop. A common structure for a loop is while (condition), where the condition can be any statement with a truth value. This means that the condition works exactly like conditions in an if statements.

In the following example, we print the numbers 1, 2, …, 10. When the value of the variable number increases above 10, the condition of the while statement is no longer true and the loop ends.

int number = 1;

while (number < 11) {
    System.out.println(number);
    number++;  // number++ means the same as number = number + 1
}

The example above can be read “as long as the variable number is less than 11, print the variable and increment it by one”.

Above, the variable number was incremented in each iteration of the loop. Generally the change can be anything, meaning that the variable used in the condition does not always need to be incremented. For example:

int number = 1024;

while (number >= 1) {
    System.out.println(number);
    number = number / 2;
}

Complete the following exercises using the while statement:

Exercise while-loop-5 : From one to a hundred

Create a program that prints the integers (whole numbers) from 1 to 100.

The program output should be:

1
2
3
(many rows of numbers here)
98
99
100

Exercise while-loop-6 : From a hundred to one

Create a program that prints the integers (whole numbers) from 100 to 1.

The program output should be:

100
99
98
(many rows of numbers here)
3
2
1

Tip: Assign the variable you use in the condition of the loop a initial value of 100 and then subtract one on each iteration of the loop.

Exercise while-loop-7 : Even numbers

Create a program that prints all even numbers between 2 and 100.

The program output should be:

2
4
6
(many rows of numbers here)
96
98
100

Exercise while-loop-8: Up to a certain number

Create a program that prints all whole numbers from 1 to the number the user enters

Up to what number? ~~3~~
1
2
3
Up to what number? ~~5~~
1
2
3
4
5

Tip: The number you read from the user now works as the upper limit in the condition of the while statement. Remember that in Java a <= b means a is less than or equal to b.

Exercise while-loop-9: Lower limit and upper limit

Create a program that asks the user for the first number and the last number and then prints all numbers between those two.

First: ~~5~~
Last: ~~8~~
5
6
7
8

If the first number is greater than the last number, the program prints nothing:

First: ~~16~~
Last: ~~12~~

Infinite loops

One of the classic errors in programming is to accidentally create an infinite loop. In the next example we try to print “Never again shall I program an eternal loop!” 10 times:

int i = 0;

while (i < 10) {
    System.out.println("Never again shall I program an eternal loop!");
}

The variable i, which determines is supposed to index the loops, is initially set to 0. The block is looped as long as the condition i < 10 is true. But something funny happens. Because the value of the variable i is never changed, the condition stays true forever.

Ending a while loop

So far, we have used the while loop with a structure similar to this:

int i = 1;
while (i < 10) {
    // Some code.
    i++;
}

With the structure above, the variable i remembers the number of times the the loop has been executed. The condition to end the loop is based on comparing the value of i.

Let us now recall how a while loop is stopped. Ending a while loop does not always need to be based on the amount of loops. The next example program asks for the user’s age. If the given age is not in the range 5-85, the program prints a message and asks for the user’s age again. As you can see, the condition for the while loop can be any expression that results in a boolean (truth value).

System.out.println("Type your age: ");

int age = Integer.parseInt(reader.nextLine());

while (age < 5 || age > 85) {  // age less than 5 OR greater than 85
    System.out.println("You are lying!");
    if (age < 5) {
        System.out.println("You are so young that you cannot know how to write!");
    } else if (age > 85) {
        System.out.println("You are so old that you cannot know how to use a computer!");
    }

    System.out.println("Type your age again: ");
    age = Integer.parseInt(reader.nextLine();
}

System.out.println("Your age is " + age);