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

The course is maintained by De Haagse Hogeschool


3. Conditional statements and truth values

So far, our programs have progressed from one command to another in a straightforward manner. In order for the program to branch to different execution paths based on e.g. user input, we need conditional statements.

int number = 11;

if (number > 10) {
    System.out.println("The number was greater than 10");
}

The condition (number > 10) evaluates into a truth value; either true or false. The if command only handles truth values. The conditional statement above is read as “if the number is greater than 10”.

Note that the if statement is not followed by semicolon as the condition path continues after the statement.

After the condition, the opening curly brace { starts a new block, which is executed if the condition is true. The block ends with a closing curly brace }. Blocks can be as long as desired.

The comparison operators are:

int number = 55;

if (number != 0) {
    System.out.println("The number was not equal to 0");
}

if (number >= 1000) {
    System.out.println("The number was greater than or equal to 1000");
}

A block can contain any code including other if statements.

int x = 45;
int number = 55;

if (number > 0) {
    System.out.println("The number is positive!");
    if (number > x) {
        System.out.println(" and greater than the value of variable x");
        System.out.println("after all, the value of variable x is " + x);
    }
}

The comparison operators can also be used outside the if statements. In such case the truth value will be stored in a truth value variable.

int first = 1;
int second = 3;

boolean isGreater = first > second;

In the example above the boolean (i.e. a truth value) variable isGreater now includes the truth value false.

A boolean variable can be used as a condition in a conditional sentence.

int first = 1;
int second = 3;

boolean isLesser = first < second;

if (isLesser) {
    System.out.println(first + " is less than " + second + "!");
}
1 is less than 3!

3.1 Code indentation

Note that the commands in the block following the if statement (i.e. the lines after the curly brace, { ) are not written at the same level as the if statement itself. They should be indented slightly to the right. Indentation happens when you press the tab key, which is located to the left of q key. When the block ends with the closing curly brace, indentation ends as well. The closing curly brace } should be on the same level as the original if statement.

The use of indentation is crucial for the readability of program code. During this course and generally everywhere, you are expected to indent the code properly. IntelliJ helps with the correct indentation. You can easily indent your program by pressing shift, alt, and f simultaneously. It’s also possible to select a whole section of code, and press tab to indent this whole section

3.2 Else

If the truth value of the comparison is false, another optional block can be executed using the else command.

int number = 4;

if (number > 5) {
    System.out.println("Your number is greater than five!");
} else {
    System.out.println("Your number is equal to or less than five!");
}
Your number is equal to or less than five!

Exercise 2-1 : A positive number

Create a program that asks the user for a number and tells if the number is positive (i.e. greater than zero).

Type a number: ~~5~~

The number is positive.
Type a number: ~~-2~~

The number is not positive.

Are you certain that your code is indented correctly?

Reread the section on code indentation. Observe what happens when you press shift, alt and f simultaneously! The same automatic indentation functionality can also be used using the menu bar by selecting Source and then Format.

Exercise 2-2 : Age of majority

Create a program that asks for the user’s age and tells whether the user has reached the age of majority (i.e. 18 years old or older).

How old are you? ~~12~~ 

You have not reached the age of majority yet!
How old are you? ~~32~~ 

You have reached the age of majority!

Exercise 2-3 : Even or odd?

Create a program that asks the user for a number and tells whether the number is even or odd. Hint: look at examples in 2.1.1.

Type a number: ~~2~~

Number 2 is even.
Type a number: ~~7~~

Number 7 is odd.

3.3 Else if

If there are more than two conditions for the program to check, it is recommended to use the else if command. It works like the else command, but with an additional condition. else if comes after the if command. There can be multiple else if commands.

int number = 3;

if (number == 1) {
    System.out.println("The number is one.");
} else if (number == 2) {
    System.out.println("The number is two.");
} else if (number == 3) {
    System.out.println("The number is three!");
} else {
    System.out.println("Quite a lot!");
}
The number is three!

Let us read out loud the example above: If number is one, print out “The number is one.”. Otherwise if the number is two, print out “The number is two.”. Otherwise if the number is three, print out “The number is three!”. Otherwise print out “Quite a lot!”.

Exercise 2-4 : Greater number

Create a program that asks the user for two numbers and prints the greater of those two. The program should also handle the case in which the two numbers are equal.

Example outputs:

Type the first number: ~~5~~
Type the second number: ~~3~~

Greater number: 5
Type the first number: ~~5~~
Type the second number: ~~8~~

Greater number: 8
Type the first number: ~~5~~
Type the second number: ~~5~~

The numbers are equal!

Exercise 2-5 : Grades and points

Create a program that gives the course grade based on the following table.

Points Grade
0-29 failed
30-34 1
35-39 2
40-44 3
45-49 4
50-60 5

Example outputs

Type the points [0-60]: ~~37~~

Grade: 2
Type the points [0-60]: ~~51~~

Grade: 5

3.4 Comparing strings

Strings cannot be compared using the equality operator (==). For string comparison, we use the equals. command, which is always associated with the string to compare.

String text = "course";

if (text.equals("marzipan")) {
    System.out.println("The variable text contains the text marzipan");
} else {
    System.out.println("The variable text does not contain the text marzipan");
}

The equals command is always attached to the string variable with a dot in between. A string variable can also be compared to another string variable.

String text = "course";
String anotherText = "horse";

if (text.equals(anotherText)) {
    System.out.println("The texts are the same!");
} else {
    System.out.println("The texts are not the same!");
}

When comparing strings, it is crucial to make sure that both string variables have been assigned some value. If a value has not been assigned, the program execution terminates with a NullPointerException error, which means that variable has no value assigned to it (null).

3.5 Logical operations

The condition statements can be made more complicated using logical operations. The logical operations are:

Below we will use the AND operation && to combine two individual conditions in order to check if the value of the variable is greater than 4 and less than 11 (i.e. in the range 5 - 10).

System.out.println("Is the number between 5-10?");
int number = 7;

if (number > 4 && number < 11) {
    System.out.println("Yes! :)");
} else {
    System.out.println("Nope :(")
}
Is the number between 5-10?
Yes! :)
Next up is the OR operation   , which will be used to check if the value is less than 0 or greater than 100. The condition evaluates to true if the value fulfills either condition.
System.out.println("Is the number less than 0 or greater than 100?");
int number = 145;

if (number < 0 || number > 100) {
    System.out.println("Yes! :)");
} else {
    System.out.println("Nope :(")
}
Is the number less than 0 or greater than 100?
Yes! :)

Now we will use the negation operation ! to negate the condition:

System.out.println("Is the string equal to 'milk'?");
String text = "water";

if (!(text.equals("milk"))) {  // true if the condition text.equals("milk") is false
    System.out.println("No!");
} else {
    System.out.println("Yes")
}
Is the text equal to 'milk'?
No!

For complicated conditions, we often need parentheses:

int number = 99;

if ((number > 0 && number < 10) || number > 100 ) {
    System.out.println("The number was in the range 1-9 or it was over 100");
} else {
    System.out.println("The number was equal to or less than 0 or it was in the range 10-99");
}
The number was equal to or less than 0 or it was in the range 10-99

Exercise 2-6 : Age check

Create a program that asks for the user’s age and checks that it is reasonable (at least 0 and at most 120).

How old are you? ~~10~~
OK
How old are you? ~~55~~
OK
How old are you? ~~-3~~
Impossible!
How old are you? ~~150~~
Impossible!

Exercise 2-7 : Usernames

Create a program that recognizes the following users:

Username Password
alex mightyducks
emily cat

The program should check for the username and password as follows:

Type your username: ~~alex~~
Type your password: ~~mightyducks~~
You are now logged into the system!
Type your username: ~~emily~~
Type your password: ~~cat~~
You are now logged into the system!
Type your username: ~~emily~~
Type your password: ~~dog~~
Your username or password was invalid!

Exercise 2-8 : Leap year

A year is a leap year if it is divisible by 4. But if the year is divisible by 100, it is a leap year only when it is also divisible by 400.

Create a program that checks whether the given year is a leap year. Make sure you only have one if-else statement, no else-if is needed

Type a year: ~~2011~~
The year is not a leap year.
Type a year: ~~2012~~
The year is a leap year.
Type a year: ~~1800~~
The year is not a leap year.
Type a year: ~~2000~~
The year is a leap year.

4. 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.

4.1 While loops

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 2-9 : 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 2-9.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 2-9.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 2-9.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 2-10 : 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 2-10.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 2-10.2: Checking

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

Exercise 2-11 : Sum of three numbers

Create a program that asks the user for three numbers and then prints their sum. Use the following structure in your program:

Scanner reader = new Scanner(System.in);
int sum = 0;
int read;

// WRITE YOUR PROGRAM HERE
// USE ONLY THE VARIABLES sum, reader AND read!

System.out.println("Sum: " + sum);
Type the first number: ~~3~~
Type the second number: ~~6~~
Type the third number: ~~12~~

Sum: 21

Exercise 2-12 : 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

Exercise 2-13 : 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.

4.1.1 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 2-14 : 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 2-15 : 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 2-16 : 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 2-17: 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 2-18: 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~~

4.1.2 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.

4.1.3 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);

4.2 Assignment operations in loops

Often during a loop, the value of a variable is calculated based on repetition. The following program calculates 3*4 somewhat clumsily as the sum 3+3+3+3:

int result = 0;

int i = 0;
while (i < 4) {
   result = result + 3;
   i++;  // means the same as i = i + 1;
}

In the beginning result = 0. During the loop, the value of the variable is incremented by 3 on each iteration. Because there are 4 iterations, the value of the variable is 3*4 in the end.

Using the assignment operator introduced above, we can achieve the same behavior as follows:

int result = 0;

int i = 0;
while (i < 4) {
   result += 3;  // this is the same as result = result + 3;
   i++;          // means the same as i = i+1;
}

Exercise 2-19: The sum of a set of numbers

Create a program that calculates the sum 1+2+3+…+n where n is a number entered by the user.

Example outputs:

Until what? ~~3~~
Sum is 6

The calculation above was: 1+2+3 = 6.

Until what? ~~7~~
Sum is 28

The calculation above was: 1+2+3+4+5+6+7 = 28.

Hint: Create the program using the while statement. Use a helper variable in your program to remember how many times the block has been executed. Use also another helper variable to store the sum. During each execution add the value of the helper variable that counts the executions to the variable in which you should collect the sum.

Exercise 2-20: The sum between two numbers

Similar to the previous exercise, except that the program should ask for both the lower and upper bound. You can assume that the users first gives the smaller number and then the greater number.

First: ~~3~~
Last: ~~5~~
The sum is 12
First: ~~2~~
Last: ~~8~~
The sum is 35

Exercise 2-21: Factorial

Create a program that calculates the factorial of the number n. The factorial n! is calculated using the formula 1×2×3×…×n. For example 4! = 1×2×3×4 = 24. Additionally, it is defined that 0! = 1.

Example outputs:

Type a number: ~~3~~
Factorial is 6
Type a number: ~~10~~
Factorial is 3628800

Exercise 2-22: Sum of the powers

Create a program that calculates the sum of , where n is a number entered by the user. The notation 2i means raising the number 2 to the power of i, for example . In Java we cannot write directly, but instead we can calculate the power with the command Math.pow(number, power). Note that the command returns a number of double type (i.e. floating point number). A double can be converted into the int type (i.e. whole number) as follows: int result = (int)Math.pow(2, 3). This assigns the value of to variable result.

Example outputs:

Type a number: ~~3~~
The result is 15
Type a number: ~~7~~
The result is 255

```

4.3 Changing the flow of execution in a loop

4.3.1 Break

It is also possible to change the flow of execution in a loop. This is done with the break and continue keywords.

The break keyword immediately breaks the loop, and jumps out of the loop. This is usually used as little as possible, as the code execution can become very chaotic with a lot of break commands. An example of using this is rewriting the code from section 11.3, which can also be written as

System.out.println("Type your age ");
int age;
while (true) {
    age = Integer.parseInt(reader.nextLine());

    if (age >= 5 && age <= 85) {  // age between 5 AND 85
        break;  // end the loop
    }

    System.out.println("You are lying!");
    if (age < 5) {
        System.out.println("You are so young that you cannot know how to write!");
    } else {  // that means age is over 85
        System.out.println("You are so old that you cannot know how to use a computer!");
    }

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

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

Note that this example uses a while(true) command, which is another bad practice

4.3.2 Continue

The continue statement jumps back to the beginning of the loop. This can be used to ‘skip’ certain values of variables. An example

int i = 0;
while (i < 100) {
    i++;
    if(i % 2 == 0) {
        continue;
    }
    if(i % 3 == 0) {
        continue;
    }
    if(i % 5 == 0) {
        continue;
    }
    System.out.println(i);
}

This example will output all values that are not dividable by 2, 3, 5. Note that the output does not include 0, as this is skipped by the i++ command.

Exercise 2-23: Loops, ending and remembering

This set of exercises will form one larger program when put together. We create the program by adding features exercise by exercise. If you do not finish all the exercises you can still send them to be reviewed by the exercise robot. To do that, click the “submit” button, which has a picture of an arrow and is located on the right of the testing button. Even though the exercise robot complains about tests in the incomplete exercises, you will still get points for the parts you have completed.

Note: from now on every sub-exercise of a larger exercise (like 36.1) has the same value as an exercise without sub-exercises. It means that exercise 36 as a whole corresponds to five normal exercises.

Exercise 2-23.1: Reading numbers

Create a program that asks the user to input numbers (integers). The program prints “Type numbers” until the user types the number -1. When the user types the number -1, the program prints “Thank you and see you later!” and ends.

Type numbers:
~~5~~
~~2~~
~~4~~
~~-1~~
Thank you and see you later!

Exercise 2-23.2: The sum of the numbers

Develop your number reading program by adding the following feature: the program should print the sum of the numbers entered by the user (without the number -1).

Type numbers:
~~5~~
~~2~~
~~4~~
~~-1~~
Thank you and see you later!
The sum is 11

Exercise 2-23.3: Summing and counting the numbers

Develop your number reading and summing program by adding the following feature: the program should print how many numbers the user typed (without the number -1).

Type numbers:
~~5~~
~~2~~
~~4~~
~~-1~~
Thank you and see you later!
The sum is 11
How many numbers: 3

Exercise 2-23.4: Counting the average

Develop your number reading, summing and counting program by adding the following feature: the program should print the average of the numbers the user typed (without the number -1).

Type numbers:
~~5~~
~~2~~
~~4~~
~~-1~~
Thank you and see you later!
The sum is 11
How many numbers: 3
Average: 3.666666666666

Exercise 2-23.5: Even and odd numbers

Develop your program by adding the following feature: the program should print the number of even and odd numbers that the user typed (without the number -1).

Type numbers:
~~5~~
~~2~~
~~4~~
~~-1~~
Thank you and see you later!
The sum is 11
How many numbers: 3
Average: 3.666666666666
Even numbers: 2
Odd numbers: 1

Note: creating a program in small steps

In these exercises we actually created one single program, but programming happened in very small steps. This is ALWAYS the preferred way to program.

When you are programming something, no matter if it is an exercise or a project of your own, it is advised to do it in very tiny pieces. Do not ever try to solve the whole problem in one go. Start with something easy, something you know that you can do. In this recent set of exercises, for example, we focused first on stopping the program when the user types -1. When one part of the program is complete and working, we can move on to work out the solution for the next sub-problem of the big main problem.

Some of the exercises in this course are sliced into smaller pieces like the set of exercises we just introduced. Usually the pieces need to be sliced again into smaller pieces depending on the problem. It is advised that you execute the whole program after almost every new line of code you write. This enables you to be sure that your solution is going in the right and working direction.

4.4 For loops

By now you will have noticed that there are usually 3 important components in a loop; the initialization, condition and increment

int i = 0;              //initialization
while(i < 10) {         //condition
    System.out.println(i);
    i++;                //increment
}

These 3 parts are key to a successful loop, and for instance, forgetting the increment will result in an infinite loop. They are split up on 3 different lines, which is not good for the structure of your code. To improve the structure, java offers a for-loop. This for-loop combines these 3 parts in a single line

for(int i = 0; i < 10; i++) {
    System.out.println(i);
}

This program is identical to the while loop. The for has all 3 different components between brackets, and is therefore different than the while() or if() conditions. This for-syntax is very powerful, but can some time getting used to. For now, you can pick if you do loops with a while() statement or a for() statement

Exercise 2-24 Checkerboard

Write a program, using for-loops, that draws a checkerboard Note that you will be using 2 for-loops here, one to iterate over the rows, and one that iterates over the columns. Note that you use # for the black tiles, and the first, topleft tile should be a #

Expected output:

# # # # # 
 # # # # #
# # # # # 
 # # # # #
# # # # # 
 # # # # #
# # # # # 
 # # # # #
# # # # # 
 # # # # #

end of week 2