Instruction Manual Programming: Seventh International Edition Published September, 2021
Instruction Manual Programming: Seventh International Edition Published September, 2021
Instruction Manual Programming: Seventh International Edition Published September, 2021
Programming
0 Syllabus 4
1
Introduction to Programming
10 SecondSmallest . . . . . . . . . . . . . . . . . . . . . . . . 25
4 Parsing input 36
Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Switch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Advanced use of the Scanner . . . . . . . . . . . . . . . . . . . . 40
Assignments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
1 Replay 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
2 Replay 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Graded Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
3 Administration . . . . . . . . . . . . . . . . . . . . . . . . 44
2
Introduction to Programming
Graded Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
3 Snake . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
7 Recursion 63
Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Assignments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
1 Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
2 Reversed Number . . . . . . . . . . . . . . . . . . . . . . 64
Graded Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
3 LongestPath . . . . . . . . . . . . . . . . . . . . . . . . . . 65
8 Bonus 68
Graded Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
1 Life . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
3
Syllabus
0
Course format
This course features a series of lectures and parallel lab sessions. During the
lectures the theory of programming is taught, during the lab sessions program-
ming is practiced by making assignments using Java. Assignments should be
prepared in advance, at home. Students will be assigned to groups. Every
group will have a teaching assistant, who will help with the assignments and
grade the graded assignments.
4
Introduction to Programming Module 0: Syllabus
• Scanner
• PrintStream
• System
5
Introduction to Programming Module 0: Syllabus
Slipdays The first three modules do not include graded assignments. There
are regular assignments to be made, so there is also a deadline in the first two
modules. You can earn a slipday if all the assignments have been approved
before the deadline (you can earn at most 2 slipdays). The first module, in
order to receive the slipday, attendance is mandatory. Slipdays can be used in
the following modules. An assignment can be turned in a day late, without
point deduction, using a slipday. Two slipdays can be used to submit a single
assignment two days late, or two assignments one day late.
Final Grade Your grade for the practical will be determined by the weighted
average of the graded assignments.
You pass the Introduction to Programming course if both your exam grade E
and practical grade P are a passing grade (≥ 5, 5). If that is the case, your fi-
nal grade for this course is calculated using the following formula: F = max(E,
(2*E+P)/3), meaning that the practical grade can not influence your final grade
negatively.
6
Editing, Compiling and Executing
1
Abstract
This module will introduce the IDE (Integrated Development Environ-
ment) Eclipse and explain how to organize Java files and execute pro-
grams.
Goals
• The use of Eclipse to open, edit, save and organize Java-files
• Compile and execute Java files
• Print source code
7
Introduction to Programming Module 1: Editing, Compiling and Executing
Introduction to Eclipse
Installing and starting Eclipse
VU Eclipse has already been installed on all the computers that will be used
during the lab sessions. Using Windows, it can be started from the Start
Menu. Using Linux, it can be started by typing eclipse in a terminal win-
dow.
At home, using Windows To use Eclipse at home, it is neccessary to install
the Java Development Kit (JDK) and Eclipse itself. It is likely that Java
has already been installed on your computer, in the form of a Java Run-
time Environment (JRE). Whilst Java programs can be executed using this
JRE, they cannot be compiled. To compile programs, a JDK is needed.
The JDK can be downloaded from Oracles website: http://www.oracle.
com/technetwork/java/javase/downloads/.
This site provides a number of different versions of the JDK: Java SE
(Standard Edition), Java EE (Enterprise Edition), Java ME (Micro Edition)
and more. For this course, Java SE will be used. Click “Download JDK”
and download the Java SE Development Kit.
To download Eclipse, browse to http://www.eclipse.org/downloads/
and download “Eclipse IDE for Java Developers”.
At home, using Linux or Mac OS X Java is installed in different ways, depend-
ing on the distribution. In a Debian-based distribution, Java can be down-
loaded from the repository. For example, using Ubuntu: open a termi-
nal window and type sudo apt-get install sun-java6-jdk. To install
Java on a different distribution, visit their support site. The JDK is already
installed on Mac OS X.
To download Eclipse, browse to http://www.eclipse.org/downloads/
and download “Eclipse IDE for Java Developers”.
Selecting a workspace The workspace is a folder in which all created files are
saved. The workspace only has to be defined once. When Eclipse is started
for the first time, it will automatically prompt for a location for the workspace.
If, for whatever reason, this does not happen, it can be done manually: File
→ Switch Workspace. The home directory is usually a good place for the
workspace /home/vunet-id/eclipse/yearone.
Arranging files
After selecting the workspace, a welcome screen will be shown. Click on Work-
bench. On the left of the current window, the Package Explorer is shown. This
frame will hold all files, sorted on Project. Every Project consists of Source Fold-
ers, whilst Source Folders consist of Packages. This may sound complicated on
first glance, but the next few steps will explain everything.
8
Introduction to Programming Module 1: Editing, Compiling and Executing
2. Create a new Source Folder. All Source Files used in one assignment will
be logically grouped together in a Source Folder. In this course, every
module will have its own Source Folder. Right-click on the project in the
Package Explorer and select New → Source Folder. Name it module1
and click Finish.
3. Every assignment will have its own Package. Right-click on the Source
Folder that was just created and select New → Package. The name of the
Package will be the same as the name of the assignment.
4. Create a new Class. Right-click on the current package and select New
→ Class. There are loads of options, but for now, only Name is relevant.
Select “public static void main” everytime you create a new program. The
first class in this course will be HelloWorld1.
import java.io.PrintStream;
class HelloWorld1 {
// Name : ...
// Assignment : HelloWorld1
// Date : ...
PrintStream out;
HelloWorld1() {
out = new PrintStream(System.out);
}
void start() {
out.printf("Hello world!! ");
out.printf("written by: %s\n", "...");
}
9
Introduction to Programming Module 1: Editing, Compiling and Executing
but be aware: Eclipse tends to do things you do not want it to do. Only use this
feature, if you understand what the error is, and how it can be solved.
Note the subtle difference between the two solutions. Using the first solu-
tion, the program will override the Locale of the environment in which it is
executed. Using the second solution, Eclipse will override the Locale of the
current environment. This means that only by using the first solution, it is
guaranteed that the program will be executed using the US Locale. In this
practical, both solutions will suffice, as it is only necessary to set the Locale to
be able to read the provided input files. All programs will be evaluated using
the US Locale and will thus not depend on the program to set the appropriate
Locale.
Trial Submission
Create a new class HelloWorld2 with a new Package HelloWorld2 and copy Hel-
loWorld1 to the Package HelloWorld2 and edit the code in the following way:
Hint: Copying files using Eclipse can be done easily using the refactor func-
tionality provided by Eclipse. For more information about refactoring, visit:
http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.jdt.
doc.user%2Fconcepts%2Fconcept-refactoring.htm
10
Introduction to Programming Module 1: Editing, Compiling and Executing
• Edit the start-method in such way that it will ask for your name:
void start() {
Scanner in = new Scanner(System.in);
Test the program. Does it work as expected? If so, you can hand it in.
Submitting Assignments
A graded assignment needs to be submitted to Practool. How to do this is
explained in the following steps:
1. Export all the files of the assignment to a .jar-file. Right-click on the Pack-
age in the Package Explorer to be exported and select Export. Select Java
→ JAR file and click Next. Make sure the name of the file starts with the
name of assignment and is followed by your VUnet-id separated by a
hyphen. For example: pirate-rhg600.jar.
Select “Export Java source files and resources?”, to ensure that the source
code is included in the jar-file. Unselect “Export generated class files
and resources”. Click Finish and the .jar-file has been created in the
workspace.
2. Did you really select “Export Java source files and resources?” and uns-
elect “Export generated class files and resources”? If not: redo step 1.
3. Surf to http://phoenix.labs.vu.nl . Choose the option ’register’ and
register. Now log in and choose the lab of your Teaching Assistent to
enroll in that particular group. Now select your group, you’ll see your
current grades and an upload option.
Warning
Assignments can only be processed if they are submitted in the format
described above. Do not submit files in any other format!
This program is not graded like the other assignments that have to be submit-
ted, however it is possible to earn a slipday if the program is submitted on
time. The syllabus provides more details on slipdays. The goal of this program
is to make sure that you can print and submit programs. These are essential
skills required during the rest of this course.
11
If statements and loops
2
Abstract
The first few programs in this module will read from standard input and
write output to standard output. These programs will be very simple. The
focus in the first part of this module will be on writing programs with
a clear layout using well chosen names. The second part of this module
will introduce if statements and loops.
Warning
This module contains ten assignments of variable size. Make sure to uti-
lize the time given to you during the lab sessions. The lab sessions only
provide sufficient time if you write your programs in advance. This way,
any problems you encounter whilst writing your programs can be re-
solved during the lab sessions.
Goals
• The use of clear identifiers.
• Familiarize with if, else and else-if statements and recognize situations in
which to apply these.
• Familiarize with for, while and do-while loops and recognize situations in
which to apply these.
Instructions
• Read the theory about Efficient programming and Constants. With this
information in mind, make the assignments VAT, Plumber 1, Plumber 2
and Othello 1.
• Read the theory about Identifiers and If-statements. With this informa-
tion in mind, make the assingments Electronics and Othello 2.
12
Introduction to Programming Module 2: If statements and loops
• Study your lecture note on Loops. With this information in mind, make
the assignments Manny, Alphabet, Collatz and SecondSmallest.
Theory
Efficient programming
Once upon a time, running a computer was so expensive that any running
time that could be saved was worthwile. Programs had to contain as few lines
of code as possible and programs were designed to run fast; clear code was
not a priority. Such a programming style is nowadays called machine-friendly.
Luckily for us, that is no longer necessary.
Programs that have been written in the past often need altering in one way or
another. If a program was written in a machine-friendly, but incomprehensible
programming style, it is almost impossible to edit it. After half a year, one
easily forgets how the program works. Imagine the problems that could occur,
if the programmer that wrote the code no longer works for the company that
wants to change it.
The direct result of this programming style is that programs are not changed
at all. Everyone has to work with the, well-intentioned, ‘features’ that are no
longer changeable.
Running programs is becoming increasingly less expensive. Programmers, on
the other hand, are only getting more expensive. Efficient programming there-
fore does not mean:
“writing programs that work as fast as possible.”
but
“writing programs that require as little effort and time possible to be
• comprehensible
• reliable
• easily maintained.”
This will be one of the major themes during this course. The Assignments that
you’ll make during this course will not be marked sufficient unless they do
what the assignment requiers them to do and meet the requirements mentioned
above.
Theory provided in this Instruction Manual is an addition to the lectures and
the book. The book contains a thorough introduction into Java mechanics, this
instruction manual will teach you how to write Java, taking the standards de-
scribed above into account.
Constants
Imagine a program that reads a number of addresses from a file and prints
them on labels - thirty characters wide, six lines high. All of the sudden, the
wholesale company changes the size of the labels to thirty-six characters wide
and five lines high.
Fortunately, the program looks like this:
13
Introduction to Programming Module 2: If statements and loops
class Labels {
// Name : ...
// Assignment : Labels
// Date : ...
// etc...
}
The only thing that needs to be done, is to change the two constants and re-
compile.
Errors that can occur when a program does not incorporate constants are:
Constants cannot only ease the maintenance of a program, but can increase the
comprehensibility of the code as well. When a constant, like LABEL_HEIGHT, is
used, it is imediately clear what this number represents, instead of only know-
ing its numerical value. For this reason, the usage of constants is very valuable.
Therefore, it is advisable to use constants in programs, even if the value of the
constant will never change.
Rule of Thumb
All numbers used in a program are constants, except 0 and 1.
Example The following example program will read a number of miles from
the standard input and prints the equivalent number of kilometers on the out-
put. Take special notice to the use of identifiers, constants and layout.
import java.util.Scanner;
import java.io.PrintStream;
class MileInKilometers {
static final double MILE_IN_KILOMETERS = 1.609344;
PrintStream out;
MileInKilometers() {
out = new PrintStream(System.out);
}
void start() {
14
Introduction to Programming Module 2: If statements and loops
Identifiers
All constants, types, variables, methods and classes have to be assigned a
name. This name is called the identifier. This identifier has to be unique within
the class it is defined in. This might seem easier than it is. In this practical you
will learn to link the correct identifier to an object.
The importance of the right name The identifier that is assigned to an object
should reflect the information it contains. When a variable is needed to main-
tain a record of the number of patients in a hospital, n would not suffice as
the identifier for this variable. The identifier n does not give any information
about this variable. When the identifier number is chosen, the problem seems to
be resolved, but is not: it is still unclear to which number the identifier refers.
Is it the number of doctors? Is it the number of beds? No, it is the number
of patients. That is why this variable should be called numberOfPatients. It
might take some time to find an appropriate identifier in some cases, but it is
certainly worth the effort. This ensures that everyone will understand your
program, including the teaching assistant.
Example A long time ago, the maximum length of identifiers was limited in
some programming languages. All information about the contents of the vari-
able had to be contained in six or seven characters. This meant that it was very
difficult to find clear and understandable identifiers. As a result, programs
were often hard to read. A program that had to find travel times in a timetable
would contain identifiers like:
int ott, // outward travel time, in minutes
rtt; // return travel time, in minutes
The introduction of programming languages like Pascal, significantly improved
the readability of code by removing the restriction on identifier lengths. Like
Pascal, Java does not limit the length of identifiers. Therefore the identifiers in
the example can be rewritten:
15
Introduction to Programming Module 2: If statements and loops
ax2 + bx + c = 0
Exceptions There are some conventions for identifiers. An example for cal-
culating the factorial of n > 0:
int factorial = n;
for(int i = n-1; i > 0; i--){
factorial *= i;
}
The identifier for the variable n is not changed into argument. Numerical ar-
guments are by convention often identified as n. Variables that are used for
iterations are similarly not identified as counter, but as i. When more than one
iterator is used, it is common practice to use j and k as identifiers for next iter-
ators.
Let’s look at another example. When programming a game of chess, the pieces
on the board can be identified by ki (king), qu (queen), ro (rook), bi (bishop), kn
(knight) and pa (pawn). Anyone a elemental knowledge of chess will surely
understand these abbreviations. However, if someone else reads this program
kn might be interpreted as king and ki as knight. This example shows the
16
Introduction to Programming Module 2: If statements and loops
Rule of Thumb
Identifiers which are used a lot in the same context, need to have a large
psychological distance.
Conventions
One important restriction for choosing identifiers is that they cannot contain
whitespace. It is common practice to write identifiers consisting of multiple
words by capitalising each word, except the first. In this practical the following
guidelines are in place:
• Names of variables, methods and functions begin with a lower case letter.
All following words are capitalised. No whitespace is used.
Example: int numberOfStudents;
Example: void start() { ... }
Example: X readX(Scanner xScanner);
• Identifiers identifying constants are written in upper case. If an identifier
for a constant consists of multiple words they are separated by under-
scores.
Example: static final int MAXIMUM_NUMBER_OF_STUDENTS = ...;
• Identifiers identifying a class are written in the same way as variables
except for the first letter, which is capitalised.
Example: class CollegeTimetable { ... }
Self test
Expressions 1
The following questions are on expressions. These questions do not need to be
turned in. Do make sure you are able to answer all the questions, as similar
questions will be asked during the exam. For all questions give the generated
output, or indicate an error. In addition write down every expression in a
question and denote the type and value of the result of the expression.
Question 1
void start() {
int result = 2 + 3;
}
17
Introduction to Programming Module 2: If statements and loops
Question 2
void start() {
double result = 1.2 * 2 + 3;
}
Question 3
void start() {
String result = "ab" + "cd";
}
Question 4
void start() {
char result = ’c’ - ’a’ + ’A’;
}
Question 5
void start() {
boolean result = true || false;
}
Question 6
void start() {
int result = 17 / 4;
}
Question 7
void start() {
int result = 17 % 4;
}
Question 8
void start() {
if (true) {
out.printf("not not true");
}
}
Question 9
void start() {
if (false) {
out.printf("really not true");
}
}
Question 10
18
Introduction to Programming Module 2: If statements and loops
void start() {
if (2 < 3) {
out.printf("2 is not larger or equal to 3");
}
}
Question 11
void start() {
if ((3 < 2 && 4 < 2 && (5 == 6 || 6 != 5)) || true) {
out.printf("too much work");
}
}
Question 12
void start() {
char number = ’7’;
out.printf("%c", number);
}
Question 13
void start() {
if (false && (3 > 2 || 7 < 14 || (5 != 6))) {
out.printf("finished quickly");
}
}
Expressions 2
The following questions are about expressions. For all questions give the gen-
erated output, or indicate an error. In addition write down every expression in
a question and denote the type and value of the result of the expression.
Question 1
double function() {
int number = 2;
return number / 3;
}
void start() {
double result = function() * 3;
}
Question 2
boolean worldUpsideDown() {
boolean numbersUpsideDown = 2 > 3;
boolean booleansUpsideDown = true == false;
19
Introduction to Programming Module 2: If statements and loops
void start() {
if (worldUpsideDown()) {
out.printf("The world is upside down!\n");
} else {
out.printf("The world is not upside down.\n");
}
}
Question 3
int awkwardNumber() {
char character = ’y’;
return ’z’ - character;
}
void start() {
out.printf("The result is awkward result: %s\n",
awkwardNumber() );
}
Question 4
void start() {
if (’a’ < ’b’) {
out.printf("smaller\n");
}
}
Question 5
void start() {
if (’a’ > ’B’) {
out.printf("hmmm\n");
}
}
Question 6
void start() {
char number = ’7’;
out.printf("%d\n", number - 1);
}
20
Introduction to Programming Module 2: If statements and loops
If-statements
Study your lecture notes on if-statements. Section 3.1 of the book will
provide additional information on if-statements.
Example This example program will read an exam grade and prints whether
this student has passed.
1 import java.util.Scanner;
2 import java.io.PrintStream;
3
4 class Passed {
5 static final double PASS_MINIMUM = 5.5;
6
7 PrintStream out;
8
9 Passed() {
10 out = new PrintStream(System.out);
11 }
12
13 void start() {
14 Scanner in = new Scanner(System.in);
15
16 out.printf("Enter a grade: ");
17 double grade = in.nextDouble();
18
19 if (grade >= PASS_MINIMUM) {
20 out.printf("The grade, %f, is a pass.\n", grade);
21 } else {
22 out.printf("The grade, %f, is not a pass.\n", grade);
23 }
24 }
25
26 public static void main(String[] argv) {
27 new Passed().start();
28 }
29 }
This example can also be implemented using a ternary operator as described
in the section Layout.
21
Introduction to Programming Module 2: If statements and loops
Assignments
1. VAT
Before starting Write a program that takes the price of an article including VAT and prints the
with this assign- price of the article without VAT. The VAT is currently 21.00%.
ment, read the
theory about Effi-
cient programming Example Using an input of 121 the output will be:1
en Constants.
Enter the price of an article including VAT: 121
This article will cost 100.00 euro without 21.00% VAT.
2. Plumber 1
The employees at plumbery ‘The Maverick Monkey’ are notorious bad math-
maticians. Therefore the boss has decided to use a computer program to calcu-
late the costs of a repair. The costs of a repair can be obtained with the following
calculation: the hourly wages multiplied by the number of billable hours plus
the call-out cost. The number of billable hours is always rounded. Plumbing
laws fix the call-out cost at e16,00.
Write a program that calculates the costs of a repair. Take the hourly wages
and number of billable hours as input for this program.
Example A plumber earning e31,50 an hour working for 5 hours should get
the following output.
Enter the hourly wages: 31.50
Enter the number of billable hours: 5
The total cost of this repair is: e173.50
3. Plumber 2
After careful assessment of the new program it turns out that the employees of
‘The Maverick Monkey’ are as bad at rounding numbers as they are at making
calculations. Therefore the boss decides to alter the program in such a way that
the program only needs the number of hours an employee has actually worked.
The program will determine the number of billable hours based on this input.
Make a copy of the previous assignment and edit the code to implement this
new feature. The number of billable hours is the number of hours worked
rounded to an integer.
Example A plumber earning e31.50 an hour, working for 4.5 hours should
get the following output.
Enter the hourly wages: 31.50
Enter the number of hours worked: 4.5
The total cost of this repair is: e173.50
22
Introduction to Programming Module 2: If statements and loops
4. Othello 1
During this course there will be multiple assignments concerning the game of
Othello, also known as Reversi.
The goal of this assignment is to give some information about the outcome
once a game has finished. This information is obtained by two measurements:
• The percentage of squares that has a black piece on it.
• The percentage of pieces on the board that are black.
The Othello board measures eight squares by eight squares, making the total
number of squares sixty-four.
Write a program that takes the number of white pieces followed by the number
of black pieces as input. Print the two percentages as output.
Example
Enter the number of white pieces on the board: 34
Enter the number of black pieces on the board: 23
The percentage of squares with a black piece is: 35.94%
The percentage of pieces that are black is: 40.35%
5. Electronics
Before starting The electrics company ‘The Battered Battery’ is nearly bankrupt. To avoid total
this assignment, disaster, the marketing branch has come up with a special sale to attract more
read the theory
about Identifiers customers. Whenever a customer buys three products, he or she receives a 15%
and If-statements. reduction on the most expensive product. Write a program that takes the prices
of three products as input and prints the discount and final price as output.
Example Determine the reduction and final price if the three products cost
e200, e50 and e25 respectively.
Enter the price of the first article: 200
Enter the price of the second article: 50
Enter the price of the third article: 25
Discount: 30.00
Total: 245.00
6. Othello 2
During a game of Othello the time a player spends thinking about his moves
is recorded. Write a program that takes the total time that two players have
thought, one human, one computer, in milliseconds as input. The program
determines which of the two players is human and prints the thinking time
of the human in the following format: hh:mm:ss. It may be assumed that a
computer takes less time to think than a human.
23
Introduction to Programming Module 2: If statements and loops
Example
Enter the time the black player thought: 234432
Enter the time the white player thought: 36
The time the human player has spent thinking is: 00:03:54.
7. Manny
Mobster Manny thinks he has found the perfect way to part money from their
The following
four assignments rightful owners, using a computer program. Mobster Manny secretly installs
use loops. Use the the program on someone’s computer and remains hidden in a corner, waiting
right loop for the
right assignment, for the program to finish. The program will ask the user how much he or she
using all the follow- wants to donate to charity: the thirsty toads in the Sahara (Manny’s Wallet).
ing loops: for, while If the unsuspecting victim wants to donate less than e50, the program will
without hasNext(), ask again. The program will continue to ask for an amount until the user has
while with hasNext()
and do-while. agreed to donate e50 or more, after which Mobster Manny will show up to
collect the money.
Write this malicious program, but make sure it does not fall in the wrong
hands.
8. Alphabet
Write a program that prints the alphabet on a single line.
9. Collatz
One of the most renowned unsolved problems is known as the Collatz conjec-
ture. The problem is stated as follows:
This next number is treated exactly as the first. This process is repeated.
An example starting with 11: 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 4 2 1 4
2 1 ...
Once the sequence has reached 1, the values repeat indefinitely. The con-
jecture is that every sequence ends with 4 2 1 4 2 1 . . .
24
Introduction to Programming Module 2: If statements and loops
Hint Use the % (modulo) operator to test whether a number is even or odd.
10. SecondSmallest
Take an unknown number of positive integers as input. Assume that the first
number is always smaller than the second, all numbers are unique and the
input consists of at least two integers. Print the second smallest integer.
Example
10 12 2 5 15
The second smallest number is:5
To denote the end of the input, press enter followed by Ctrl-Z (Windows) or
Ctrl-D (Linux and OSX).
25
Methods and functions
3
Abstract
The programs written in the previous module use if-statements and
loops. Writing complicated programs with these statements will quickly
result in confusing code. Introducing methods and functions to the code
can solve this problem. This module will provide the neccesary knowl-
edge on how to use these and more importantly, on how to structure the
code.
Goals
• Familiarize with methods, functions and parameters.
• Use methods and functions to structure programs.
Instructions
• Read the theory about Methods and functions. With this knowledge
in mind, make the assignments NuclearPowerPlant, RepeatCharacter 1,
RepeatCharacter 2, Pyramid and Pizza.
• Make sure to import the library libUI.jar into Eclipse as described in Im-
porting the libUI.jar. Now make the graded assignment Replay 1.
26
Introduction to Programming Module 3: Methods and functions
Theory
Methods and functions
The theory on how methods work, what they are used for and how to call them
has been explained in the lectures. A method call is just another statement.
The execution of this statement is slightly more complicated than the execution
of a normal Java statement; instead of executing a single statement, a whole
method, possibly calling other methods, has to be executed. The great thing
about using methods is that at the moment that a method is called, it does not
matter how the method is executed. The only thing that matters is what the
method does, and not how the method does this.
An example. A program that translates Dutch text into flawless English will
no doubt feature a piece of code like this:
class TranslateDutchToEnglish {
void start() {
while (in.hasNext()) {
String dutchSentence = readSentence();
String englishSentence = translateSentence(dutchSentence);
writeSentence(englishSentence);
}
}
// etc
}
It is very unlikely that someone will doubt the correct execution of this piece
of code. Whilst writing a part of the program, it is assumed that the methods
readSentence(), translateSentence() and writeSentence() exist. How these meth-
ods work, does not matter. Without knowing how these methods work, it cán
be concluded that this piece of code is correct.
The method readSentence() is not that difficult to write. A sketch of this method:
String readSentence() {
/* Returns a Dutch sentence. */
while (!endOfSentence()) {
sentence += " " + readWord();
}
return sentence;
}
Methods are used to split the program in smaller parts, that have a clear and
defined function. This can all be done without knowing how other methods
do what they are supposed to do. When writing a part of the program, it is
important not to be distracted by a detailed implementation somewhere else in
the program. This also works the other way around. When writing a method,
it is not important what it is used for in the part of the program that calls it. The
only thing that matters, is that the method does exactly what it is supposed to
do according to the method name.
27
Introduction to Programming Module 3: Methods and functions
Small pieces of code can easily be understood and can be checked easily whether
they do what they are supposed to do.
Rule of Thumb
A method consists of no more than 15 lines.
28
Introduction to Programming Module 3: Methods and functions
29
Introduction to Programming Module 3: Methods and functions
78 }
If you have trouble importing the LibUI, feel free to ask your teaching assistant
for help.
Import-statements can now enable the use of specific elements of the UI-library.
This works similarly to import-statements for the Scanner and PrintStream classes.
For example, the program requires the UserInterfaceFactory from the libUI.jar. To
enable this class to be used, add the following line to the top of the program:
import ui.UserInterfaceFactory;
Selecting input using the UserInterface Using the libUI.jar library, Eclipse
can use files as input instead of the standard input, the keyboard. To select a file
as input, the askUserForInput().getScanner() method is used. This method can
be found in the UIAuxiliaryMethods class. Add the following line to the top of
the program:
import ui.UIAuxiliaryMethods;
and add the following statement to the top of the start method:
Scanner fileScanner = UIAuxiliaryMethods.askUserForInput().getScanner();
When a program is executed that includes the above mentioned statement, the
program will open a browser to select the input file. Browse to the location of
the file and press Enter. The Scanner fileScanner can now be used to read the
content of the selected file.
30
Introduction to Programming Module 3: Methods and functions
31
Introduction to Programming Module 3: Methods and functions
Assignments
1. NuclearPowerPlant
Before starting The nuclear powerplant at Threeyedfish will automatically run a program to
this assignment, print a warning message when the reactor core becomes unstable. The warning
read the theory
on Methods and message reads:
functions. NUCLEAR CORE UNSTABLE!!!
Quarantine is in effect.
Surrounding hamlets will be evacuated.
Anti-radiationsuits and iodine pills are mandatory.
Since the message contains crucial information, it should be printed three times.
Write a program that prints this message three times using a single method. Do
not use duplicate code. Seperate every warning message by a blank line.
2. RepeatCharacter 1
Write a program that will:
3. RepeatCharacter 2
This assignment takes of where RepeatCharacter1 has finished. Make a copy of
RepeatCharacter1 and edit the code so that the program will:
Solve this problem with as little change to the previous program as possible.
One method should suffice.
4. Pyramid
Write a program that prints a pyramid made of letters in the middle of the
screen. Use methods with parameters for this assignment. The example shows
the expected output, a pyramid of 15 levels. It can be assumed that the screen
width is 80 characters.
32
Introduction to Programming Module 3: Methods and functions
Example
a
bbb
ccccc
ddddddd
eeeeeeeee
fffffffffff
ggggggggggggg
hhhhhhhhhhhhhhh
iiiiiiiiiiiiiiiii
jjjjjjjjjjjjjjjjjjj
kkkkkkkkkkkkkkkkkkkkk
lllllllllllllllllllllll
mmmmmmmmmmmmmmmmmmmmmmmmm
nnnnnnnnnnnnnnnnnnnnnnnnnnn
ooooooooooooooooooooooooooooo
5. Pizza
Mario owns a pizzaria. Mario makes all of his pizzas with 10 different ingredi-
ents, using 3 ingredients on each pizza. Mario’s cousin Luigi owns a pizzaria
as well. Luigi makes all his pizzas with 9 ingredients, using 4 ingredients on
each pizza. Mario and Luigi made a bet: Mario believes that customers can
order more pizzas in his pizzaria than they can order in Luigi’s pizzaria.
Write a program that calculates the winner of this bet. Use functions for this
assignment.
Hint When choosing k items from n possible items, the number of possibili-
ties can be obtained using the following formula:
n n!
=
k k!(n − k)!
33
Introduction to Programming Module 3: Methods and functions
Graded Assignment
6. Replay 1
The goal of this assignment is to write a program that can replay a game of
Starting whith
this assignment, a lot Othello. The input file contains all the changes that have been made to the
of assignments will board in every turn. All the changes that are made during a turn are to be
be using the library
libUI.jar and read in- visualized on screen.
put from a file. In-
struction on how to Read and process one line of the input file at a time, letting the changes take
do this in Eclipse can place on the board. After each turn, the game halts as long as it has been
be found in Import-
ing the libUI.jar. instructed to by the input file. When the end of the file is reached, the game
has finished.
The game starts with four stones in the center of the screen. Two white stones
at d 4 and e 5 and two black stones at d 5 and e 4. Make sure that these stones
are present before processing any turns.
The line starts with indicating which player played this turn. The next number
indicates the thinking time in milliseconds. After this there is either the word
"move" or "pass". Stones are only being placed when a turn is not passsed. The
coordinate following a waiting time > 0 is the stone placed by the player cur-
rently playing. All other coordinates by the same player are captured stones.
34
Introduction to Programming Module 3: Methods and functions
Example The following example shows a piece of code placing a white stone
in the top-left corner, a black stone in the bottom-left corner, waiting 5 seconds,
changing the white stone in the top-left corner to black and finally deleting the
black stone in the bottom-right corner.
1 import ui.OthelloReplayUserInterface;
2 import ui.UserInterfaceFactory;
3
4 class UIExample {
5 static final int WAITING_TIME = 5000; // in milliseconds
6
7 OthelloReplayUserInterface ui;
8
9 UIExample() {
10 ui = UserInterfaceFactory.getOthelloReplayUI();
11 }
12
13 void start() {
14 ui.place(0, 0, ui.WHITE);
15 ui.place(ui.NUMBER_OF_COLUMNS - 1, ui.NUMBER_OF_ROWS - 1,
16 ui.BLACK);
17 ui.showChanges();
18
19 ui.wait(WAITING_TIME);
20
21 ui.place(0, 0, ui.BLACK);
22 ui.place(ui.NUMBER_OF_COLUMNS - 1, ui.NUMBER_OF_ROWS - 1,
23 ui.EMPTY);
24 ui.showChanges();
25 }
26
27 public static void main(String[] argv) {
28 new UIExample().start();
29 }
30 }
35
Parsing input
4
Abstract
A lot of programs depend on some sort of input. In previous modules
the Scanner was used to read numbers. This module will introduce struc-
tured reading of structured input to parse complex input and write struc-
tured programs.
Goals
• Use next(), nextLine() and useDelimiter() from the Scanner class to read
structured input.
• Write well structured code that reflects the way the input is parsed.
36
Introduction to Programming Module 4: Parsing input
Theory
Layout
A good layout is essential to make comprehensible programs. There are many
different layouts that will result in clear programs. There is no single ’best
layout’, it is important though to maintain the same layout throughout the
whole program. Examples of a good layout can be found in all the examples in
the book and in this instruction manual. A couple of rules of thumb:
Rule of Thumb
A } is always aligned vertically below the corresponding method, for,
while, if or switch statements. The keyword itself is not indented. All code
in the body of these control statements is indented by four or eight spaces,
usually the width of one or two tabs.
Rule of Thumb
Methods are separated by at least one white line. The declaration of vari-
ables and assignments are also separated by a white line. White lines can
be added anywhere, if this increases clarity.
if (boolean expression) {
statement;
} else {
statement;
}
if (boolean expression) {
a lot of statements
...
} else { // opposite of the boolean expression
statements
...
}
37
Introduction to Programming Module 4: Parsing input
if (boolean expression 1) {
statement 1;
}
else if (boolean expression 2) {
statement 2;
}
else if (boolean expression 3) {
statement 3;
}
else { // explanation on the remaining cases
statement 4;
}
Switch
The switch-statement can be used when a choice between different pieces of
code is made, based on a value.
int a = ...;
switch (a) {
case 1:
statement 1;
break;
case 2:
statement 2;
break;
case 3:
statement 3;
break;
default:
explain all remaining cases
statement 4;
}
The switch-statement can only be used in combination with primitive types like
integers and characters. Using the switch-statement in combination with strings
will not work as expected. In addition to this restriction, the switch-statement
can only be used when checking the value for equality (==); this example uses
(a == 1), (a == 2) and (a == 3). Other expressions, like < or >, can only be
achieved by using if-statements.
38
Introduction to Programming Module 4: Parsing input
Comments
"Comments make sure a program is readable. Everyone knows this. In the
past, when only very few could program, sometimes someone would write a
program without comments. Now this is often considered as old-fashioned,
maybe even offensive. Better safe than sorry and add some extra comments."
Wrong!
It can be assumed the reader can understand Java. A clear piece of code does
not need additional explanation.
However, there are some cases in which it is advisable to add comments, in the
middle of a method (for example, the previous if-statements). Though usually
comments are placed at the top of the method. These comments are usually
placed to explain a complex method, describing:
• what the method does
• (if neccessary) how it does this
• (if neccessary) how the method changes external values. If, for example, a
global variable is changed within the method, it might be useful to write
this in a comment.
A well written program contains a lot of methods without any comments. Usu-
ally, the name of a method will indicate precisely what will happen and the
code will be readable. For example:
void print(int[] row);
does not require explanation telling the reader that a row is printed. However,
the method
/* Sorts the list using "rapidsort";
* see Instruction Manual.
*/
void sort(int[] row) {
39
Introduction to Programming Module 4: Parsing input
Rule of Thumb
If the name of the method explains what it does and it is trivial how it does
this, no comments are neccessary.
If one or both of the prerequisites are not met, a comment is needed.
There are very little or no comments within a method.
Reading from a string Scanners made with the new Scanner(System.in) state-
ment read from standard input, the keyboard. Scanners made with a new Scanner(string)
statement will read from the defined string. It is possible to create Scanners that
read from a string, read by another Scanner. For example:
Scanner in = new Scanner("a,b,c,d 2#4#6#8");
String letters = in.next();
String numbers = in.next();
40
Introduction to Programming Module 4: Parsing input
numberScanner.useDelimiter("#");
// read all the numbers, and print the sum of all the numbers.
int sum = 0;
while (numberScanner.hasNext()) {
sum += numberScanner.nextInt();
}
out.printf("%d\n", sum);
Example Input is often structured, this means that the input is made up of
different parts, often again divided in seperate parts, and so on and so forth.
Such input can be read in a structured way by first reading the large parts and
forwarding these parts to a different method that will read the sub-parts.
ExampleProgram() {
out = new PrintStream(System.out);
}
41
Introduction to Programming Module 4: Parsing input
printAddress(addressScanner);
}
void start() {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
String student = in.nextLine();
Scanner studentScanner = new Scanner(student);
printStudent(studentScanner);
}
}
42
Introduction to Programming Module 4: Parsing input
Assignments
1. Replay 2
The input of Replay1 was structured like this:
Before starting
this assignment,
read the theory black 1035 move b 3
about Advanced use black 0 move c 3
of the Scanner. black 0 move d 3
etc...
In this arrangement, every line consists of a turn, and every turn consists of
multiple coordinates. Make a copy of Replay1 and edit the code such that it
can handle this new arrangement. In addition, print the number of pieces that
have been conquered during each turn. The Javadoc describes how to print in
the status bar of the OthelloReplayUserInterface.
Example
black: conquered 2 pieces
white: conquered 3 pieces
black: passed
white: conquered 0 pieces
2. Replay 3
For this assignment, multiple games of Othello have been combined into a sin-
gle file, separated by a ’=’. This file can be found on Canvas. Make a copy of
Replay2 and edit the code in such a way that it can handle this input file.
Games should be played one after another, waiting five secconds between the
end of one game and the start of another. Before starting a new game, make
sure to erase the board and status bar. Information on how to achieve this can
be found in the Javadoc.
43
Introduction to Programming Module 4: Parsing input
Graded Assignment
3. Administration
For the end of year administration of Programming for History of Arts students
you are to write a program that has 2 functions:
1. calculate a final grade
2. print a small graph of similarity scores and, if applicable, list the students
under investigation
The input is structured as follows:
Piet van Gogh_5 6 7 4 5 6
5=20=22=10=2=0=0=1=0=1;Vincent Appel,Johannes Mondriaan
Karel van Rijn_7 8 6 6
2=30=15=8=4=3=2=0=0=0;
You have to calculate the final grade of the student. All grades have the
same weight. The final grade is rounded as follows:
The first 10 numbers are the similarity scores. These scores represent the
number of programs matching a certain percentage of the current program in
steps of 10%. This means the first numbers indicates the matches from 1%-10%
and the last number indicates the matches from 91%-100%.
Since this is not very readable, the professor would like a simple graph
according to these rules:
The names of the students after the semicolon are the names of the students
with matches in the final 3 categories. The names of these students should be
printed under the graph. If there are no matches, the program should print
"No matches found".
The output for the aforementioned input should be:
44
Introduction to Programming Module 4: Parsing input
45
Arrays and classes
5
Abstract
In the previous modules methods and functions were used to structure
a program. For the more advanced programms another way to struc-
ture a program is by using classes. Classes are used to join a number of
relating methods and variables. With classes it is possible to represent
real-world objects. Because classes can be used for this, Java is called an
object-oriented programming language. This module shows how to use
classes.
Goals
• Using arrays to save a(n) (un)known number of values.
46
Introduction to Programming Module 5: Arrays and classes
Theory
Classes
Complex programs almost always require the use of two or more classes. Each
class contains a number of logically connected data and/or methods. Two
types of classes can be distinguished:
2. Secondly, classes that define an object from the real world. An example of
such a class is the class Person. This class could contain data like: name,
address, date of birth, etc. In addition, this class could contain a function
int age(), which returns the age of this person by using the date of birth
and the current date. Another example of such a class is Circle. This class
contains a center and a radius. Methods that are logically connected to
this class are for example double surfaceArea() and double circumference().
In the first four modules, only classes of the first category were required. As-
signments from this module onwards will also use classes from the second
category. An example will show how to create and use such a second class. It
is good practice to use separate files for different classes.
Example This example will feature a program used by airline ‘FlyLo’ to cal-
culate the profit of a flight to London. The airline uses four different fares:
1. Toddlers, aged 0 to 4 years old are charged 10% of the regular fare.
2. Children, aged 5 to 12 years old are charged half the regular fare.
3. Adults are charged the regular fare.
4. Elderly peoply, aged 65 years or more pay an extra 10% on top of the
regular fare, as they have more money anyway.
The regular fare for a single ticket to London is e99. A Boeing 747, the largest
plane in the airline’s fleet, will accomodate 400 passengers.
The airline wants to know what consequences a change in the maximum age of
a toddler may have. The airline wants to know what the new profit of a flight
will be, and if there is an increase or decrease in the profit.
The program uses a two-line input. The first line contains all the passenger’s
ages. The second line contains the new maximum toddler age. The program
will print the two profits and the difference between these two. It is useful to
save all the ages in a row. This way, the row can simply be ‘asked’ how many
passengers will fit each category. This data will allow the program to calculate
the total profit. A row, such as the one proposed above is a good example of
a second class. The class holds data, the ages of all the passengers and the
number of passengers. Apart from the constructor, the class has a method to
47
Introduction to Programming Module 5: Arrays and classes
add an age to the row and a method to calculate how many passengers fit into
a certain category.
This row can be implemented using an array, which does not necessarily have
to be completely filled. This means that the number of ages currently saved in
the array has to be maintained. The method add() will add a new age to the
back of the row. The function int numberInRange(int startingAge, int endingAge)
calculates the number of passengers that fit this range. The methods AgeRow
readAgeRow() and double calculateTotalProfit() are self-explanatory.
class AgeRow {
static final int MAX_NUMBER_OF_PASSENGERS = 400;
int[] ageArray;
int numberOfPassengers;
AgeRow() {
ageArray = new int[MAX_NUMBER_OF_PASSENGERS];
numberOfPassengers = 0;
}
int result = 0;
48
Introduction to Programming Module 5: Arrays and classes
import java.io.PrintStream;
import java.util.Scanner;
class Airplane {
// Name : Martijn Bot
// Assignment: Airplane
// Date : August 6th 1997
PrintStream out;
Airplane() {
out = new PrintStream(System.out);
}
49
Introduction to Programming Module 5: Arrays and classes
void start() {
Scanner in = new Scanner(System.in);
printChangeInProfit(normalProfit, newProfit);
}
50
Introduction to Programming Module 5: Arrays and classes
Assignments
1. Array
Read exactly twenty numbers from standard input and print them in reversed
order. Do not use a second class yet.
2. BodyMassIndex
Professor Hatzelklatzer has researched the extremely rare Hatzelklatzer-sydrome.
There seem to be fewer cases of the sydrome in odd months than in even
months. Further research should reveal if the syndrome affects people more
often if they are too heavy.
A way of determining whether someone is too heavy is the body-mass index
(BMI). This is a measure of a person’s weight taking into account their height.
The BMI is defined as weight/length2 . The World Health Organization (WHO)
considers a BMI between 18,5 and 25 as ideal and considers people with such
a BMI healthy.
The program receives input consisting of two persons with their name, sex,
length and weight.
Dean Johnson M 1.78 83
Sophia Miller V 1.69 60
Process this input into structured data. To achieve this, use an useful extra class
with useful methods to enhance the structure of the program. Use this struc-
tured data to print for each person: an appropriate style of address, surname,
the BMI and a statement whether this is considered healthy or not.
Example
Mr. Johnson’s BMI is 26.2 and is unhealthy.
Mrs. Miller’s BMI is 21.0 and is healthy.
3. Reverse
The input for this assignment consists of two rows of an unknown number of
numbers, at most 20, at least 1. A row is printed on a single line, with the
numbers separated by spaces.
Reverse the rows and print them on standard output. Next, print the largest
number of each row and print which row has the largest number.
Example
5821
-100 100 200
1 2 8 5
200 100 -100
Largest number of row 1: 8
Largest number of row 2: 200
The largest number is in row 2.
51
Introduction to Programming Module 5: Arrays and classes
Graded Assignment
4. Travel Distance
For the annual scavenger hunt and puzzle race, each contestant is given a file
that contains some number of coordinates. The contestants have to visit these
coordinates in a certain order, but that order is different from the order in which
the coordinates appear in the file.
The first line of the file contains a coordinate (in the form x,y). Each other line
starts with the letter b or f, followed by a coordinate. In order to find the correct
route, start off with the coordinate on the first line. Then go over the rest of the
lines. If a line starts off with the letter f, put the following coordinate in front
of the route. If the line starts with the letter b, put the following coordinate to
the back of the route.
Write a program that can read such an input file, and find the correct route. You
should write a class called Coordinate, and a class called CoordinateRow. The
CoordinateRow class should contain methods to add a coordinate to the front
or the back of the row, which you can use to put the coordinates in the correct
order. The program should print the correct route, and the total distance of that
route. You can assume that you can always travel in a straight line from one
coordinate to the other, meaning that you can calculate the distance using the
Pythagorean theorem.
52
Events and animations
6
Abstract
This module introduces events and animations. These notions are es-
sential for programming interactive programs. The graded assignment
of this module will involve programming the game Snake. A game such
as Snake is quite complex and therefore it requires a careful approach.
Using stepwise refinement one begins with a rough sketch of a program,
which is developed with increasing detail. Before starting with pro-
gramming the graded assignment it is compulsary to make such a sketch
of the program, which has to be approved before being allowed to con-
tinue.
Goals
• Familiarize with events.
• Use events to program an animated program.
• Use events to program an interactive program.
53
Introduction to Programming Module 6: Events and animations
Theory
Events
The Replay assignment introduced the Graphical User Interface (GUI). This
program was not interactive, it did not react to input provided by the user.
To make a program interact with the user, this course uses events. An event is
for example a mouse-click, a keystroke or even the fact that it is 2 o’clock.
Using the following functions from the GUI will allow the program to work
with events.
Event getEvent();
Calling this function will make the program halt and wait for an event to arise.
After an event has risen, the function returns an Event-object containing infor-
mation on the event. The Event class looks like this:
class Event {
String name;
String data;
}
Pressing the letter ’a’ will generate an Event-object containing the name "letter"
and the data "a". Clicking field 4,3 will return an Event-object containing the
name "click" and the data "4 3".
The method processEvent needs to determine what has happened, and what
should happen as a result. Such a method, that calls different methods accord-
ing to a specific condition is called a dispatch-method.
void processEvent(Event event) {
if (event.name.equals("click")) {
processClick(event.data);
} else if (event1) {
processEvent1(event.data);
} else if (event2) {
processEvent2(event.data);
} else {
....
} else {
54
Introduction to Programming Module 6: Events and animations
....
}
}
More information on the UserInterface can be found at https://phoenix.
labs.vu.nl/doc/java/doc/.
Animations
The way events have been used so far, only allows the program to react to
input given by the user. It is not possible for the program to change anything
on the screen on it’s own account. In order to program an animated program, a
program has to be able to do something without requiring input from the user.
A program is animated when it does not require events produced by the user
to make changes to the screen. This means a program is not animated if the
screen changes very rapidly because of a lot of events produced by the user.
The first animated program during this course was the Replay assignment. A
game of Othello was replayed without any input from the user.
Computer games like snake are called interactive animations. In these pro-
grams, the user can influence an animation. In the Replay assignment, the wait()
method was used to regulate the speed of the animation. This approach is not
useable for interactive animation, as the whole program halts when the wait()
method is executed. The program cannot react to events, not even those gener-
ated by the user. Waiting for ten seconds, will cause a mouse-click for example
to be processed with a ten seccond delay. To solve this issue, the SnakeUserIn-
terface contains the following method:
void setFramesPerSecond(double framesPerSecond);
When this method is called with, for example 24.0 frames per second, the
program will generate 24 events per second. These events all have the name
"alarm" and data "refresh". The program can now be made to react to these
events by refreshing the screen. This way, the wait() method does not have to
be used, and events generated by the user can be processed instantly.
Stepwise Refinement
An important part of writing structured programs is stepwise refinement. This
can be roughly defined in the following way:
• Write down exactly what the program should do, in English or in another
natural language.
• Next, step by step elaborate on the description of the program. Again,
write in a natural language, or, when it is trivial, directly in Java.
• This process is repeated until the whole program is written in Java.
When the algorithm is correctly executed, the result will be a flawless struc-
tured program.
55
Introduction to Programming Module 6: Events and animations
Example Write a program that reads a date in the format: day month year,
separated by spaces. The program prints whether the date is correct. This
program will be made using stepwise refinement. Important to note is that all
programs execute precisely the same assignment. The only difference is the
amount of English replaced by Java.
Program 1
class CheckDate {
CheckDate() {
}
void start() {
// read the date
// check the date
// print output
}
Program 2
import java.util.Scanner;
import java.io.PrintStream;
class CheckDate {
PrintStream out;
CheckDate() {
out = new PrintStream(System.out);
}
void start() {
Scanner in = new Scanner(System.in);
56
Introduction to Programming Module 6: Events and animations
Program 3
import java.io.PrintStream;
import java.util.Scanner;
class CheckDate {
PrintStream out;
CheckDate() {
out = new PrintStream(System.out);
}
57
Introduction to Programming Module 6: Events and animations
return result;
}
void start() {
Scanner in = new Scanner(System.in);
Program 4
import java.io.PrintStream;
import java.util.Scanner;
class CheckDate {
PrintStream out;
CheckDate() {
out = new PrintStream(System.out);
}
58
Introduction to Programming Module 6: Events and animations
return result;
}
void start() {
Scanner in = new Scanner(System.in);
59
Introduction to Programming Module 6: Events and animations
Assignments
1. Events
Before starting Write a program using a SnakeUserInterface of 40 × 30 which has the following
this assignment, features:
read the theory
about Events.
• Clicking on a square results in a piece of wall to be placed on that square.
• Pressing the space bar erases all the walls.
• The program prints the name and data of all events that occur.
2. Animation
Before starting The goal of this assignment is to make an animated program in which a piece
this assignment, of wall moves across the screen. The piece of wall starts out on (0,0) and moves
read the theory
about Animations right a square at a time. Upon reaching the end of a row, the piece of wall will
move to the first square of the next row. When the piece off wall reaches the
end of the last row, it is transferred back to the initial (0,0) position.
On top of this make sure the program implements the following features:
• The animation should slow down 0.5 frames per second when ← (left
arrow) is pressed.
• The animation should speed up 0.5 frames per second when → (right
arrow) is pressed.
• The piece of wall should change into a green sphere (a part of a snake)
when g is pressed. Pressing g again will revert the change.
Example
1 2 3 4 5
6 7 8 9 10
60
Introduction to Programming Module 6: Events and animations
Graded Assignment
3. Snake
Before starting A logical step forward from interactive animated programs is games. The goal
this assignment, of this assignment is to program the classic computer game, Snake.
read the theory
about Stepwise The goal of Snake is to create a snake as long as possible. This is achieved by
Refinement. In guiding the snake to apples, lying about on the field. The snake cannot stop
addition, before moving, and dies whenever it hits something. Because the snake is growing
starting with pro- longer and longer as the game progresses, it is increasingly difficult to avoid
gramming, a draft of
the program has to collisions with the snake itself.
be approved. At the start of the game, the snake consists of two pieces at the coordinates (0,0)
and (0,1). As said before, the snake is always moving. At the start of the game,
it moves to the right. When the user presses one of the arrow keys, the snake
changes direction.
At every moment in the game, there is always an apple somewhere in the field.
If the snake hits an apple, the snake becomes one piece longer at the next screen
refresh. A new apple is placed on a random location, excluding all places cov-
ered by the snake.
When the snake reaches the end of the screen, it will re-emerge at the other
end.
Note that if the snake goes into a certain direction, it can’t move in the opposite
direction within one refresh (so for instance, if the snake goes right, and you
click left, nothing should happen). Also within one refresh the snake can’t
change direction more than once.
Example The example below shows a short game of snake, played on a 4x3
field. The game to be designed in this assignment will have a field measuring
32x24. The arrow indicates in which direction the snake is travelling. The
numbers on the snake indicate its position in the row.
startingposition → ↓ ←
← ↑ ↑ ↑
61
Introduction to Programming Module 6: Events and animations
Bonus Edit the program in such a way that it accepts a level as input. A level
defines a number of walls, which the player has to avoid. Levels can be found
on Canvas. The structure of these files is as follows: <the coordinates at which
the snake starts, starting with the head of the snake>=<the initial direction of
the snake>=<the coordinates of the walls>.
Coordinates are formatted in the following way: one coordinate per line, in
the format: <x><space><y>. The initial direction is one of four strings: "L"
(Left), "R" (Right), "U" (Up) of "D" (Down).
An example of a piece of such a file:
1 0
0 0=R=3 3
4 3
5 3
6 3
7 3
8 3
etc...
62
Recursion
7
Abstract
When a method or function makes a call to the same method or function,
it is called recursion. In some cases a complex problem can be solved by
recursively solving similar subproblems. The graded assignment of this
module uses recursion to solve the problem of finding the longest track
in a labyrinth in an elegant way.
Goals
• Understand the notion of recursion
63
Introduction to Programming Module 7: Recursion
Assignments
1. Numbers
Print the numbers 10 to 1 in a recursive way. Next, adapt the recursive function
to print the numbers 1 to 10. Using this knowledge, write a combined recursive
function that prints the numbers 10 to 1 followed by the numbers 1 to 10. One
method should suffice to solve this problem.
Example The output of the final program should look like this:
10 9 8 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8 9 10
2. Reversed Number
Take a large number as input and print it in reverse on the output. Zeros at the
end of a number should also be visible at the start of the reversed number.
Example
123456780
087654321
64
Introduction to Programming Module 7: Recursion
Graded Assignment
3. LongestPath
One of the uses of recursive programming is searching the best solution by try-
ing all possible solutions. Examples include searching for a solution of a Ru-
bik’s Cube or the best possible next move in a game of Othello. The goal of this
assignment is to find the longest path that can be traced through a labyrinth
without visiting the same place twice.
A number of labyrinths can be found on Canvas. This is an example of such a
file:
1 1=30 22=31 23
31 4
31 3
31 2
31 1
31 0
30 0
29 0
The process of searching for the longest path should be visible on screen. This
means that every change in the current path should be shown on screen. To
find the longest path, use the following steps:
The following example shows the tracing of all possible paths in a small labyrinth.
It uses the steps described above. It tries all directions in the following order:
west, south, east, north.
65
Introduction to Programming Module 7: Recursion
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
66
Introduction to Programming Module 7: Recursion
67
Bonus
8
Abstract
This module contains the bonus assignment. Students who complete
the bonus assignment suffuciently will be given one tenth of the bonus
grade on top of their lab grade.
Warning
As this is a bonus assignment, there is no time reserved for this assignment
during the lab sessions. This assignment is solely meant for those students
who have finished all other assignments. Students are only allowed to
start on this assignment if all other assignments have been submitted.
Graded Assignment
1. Life
The Game of Life was invented by J.H. Conway. Two publications in the “Sci-
entific American” by Martin Gardner saw the game introduced to the public.
Life is played on a board of n x n squares, representing a population of dead
and living cells. A living cell can either die or continue to live, based on a set
of rules. A dead cell can either become alive again, or remain dead. Every cell
has eight neighbours, except the cells on the edge of the board:
1 2 3
4 * 5
6 7 8
68
Introduction to Programming Module 8: Bonus
1 2 3
4 5 6
7 8 9
10 11 12
13 14
69
Introduction to Programming Module 8: Bonus
It is possible for a figure to die (an empty board) or become an oscillator, i.e.
generation n = generation n + p, for any n above a certain value. If the period
equals 1 (p=1), it is called a still figure.
Write a program that takes a starting configuration from a file and generates
generations as long as the figure has not died, become an oscillator with a cer-
tain p, or exceeds the maximum number of generations. When the program
terminates, print a message stating why the program has terminated and if the
figure has become an oscillator, its period. If the period of the oscillator is 1,
the message should read “Still figure” instead of “Oscillator”. The input files
on Canvas have the following structure:
This assignment uses the LifeUserInterface. This works exactly like the Re-
playUserInterface. The only difference are the constants declaring the images:
LifeUserInterface.DEAD and LifeUserInterface.ALIVE. The LifeUserInterface
can be intialized with UserInterfaceFactory.getLifeUI(width,height).
70