• No results found

Assignment 1: Meet Dodo

N/A
N/A
Protected

Academic year: 2021

Share "Assignment 1: Meet Dodo"

Copied!
29
0
0

Bezig met laden.... (Bekijk nu de volledige tekst)

Hele tekst

(1)

Algorithmic Thinking and Structured Programming (in Greenfoot)

© 2017 Renske Smetsers-Weeda & Sjaak Smetsers1

Contents

Introduction 1

Learning objectives 2

Instructions 2

Theory 3

1.1 Dodo’s world . . . 3

1.2 Objects . . . 3

1.3 Algorithms . . . 4

1.4 Methods . . . 4

1.5 Classes and inheritance . . . 4

1.6 The state of an object . . . 5

1.7 Parameters and results . . . 6

1.8 Signatures . . . 7

1.9 Reading flowchart and code . . . 7

1.10 Java Documentation . . . 9

1.11 Modifying, compiling and testing programs . . . 10

1.12 Naming conventions . . . 11

1.13 Errors . . . 12

1.14 Printing to the console . . . 12

Challenges 14 1.1 Getting started with Greenfoot . . . 14

1.2 Creating objects . . . 15

1.3 Exploring the accessor method . . . 15

1.4 Exploring the mutator method . . . 16

1.5 Inheritance . . . 17

1.6 States . . . 17

1.7 Calling Accessor Methods . . . 18

1.8 Using Parameters . . . 18

1Licensed under the Creative Commons Attribution 4.0 license:https://creativecommons.org/licenses/by/4.0/

(2)

1.9 Reading a flowchart and its corresponding code . . . 19

1.10 Adding a new method turn180() . . . 20

1.11 Error messages . . . 21

1.12 Printing text to the console . . . 21

1.13 Printing variables to the console . . . 22

1.14 Printing coordinates to the console . . . 22

Reflection 24

Diagnostic Test 25

Saving and Handing in 27

(3)

Introduction

In this series of assignments, Algorithmic Thinking and Structured Programming (in Greenfoot), you will learn Algorithmic Thinking and the basics of Object Oriented programming...and (hopefully will) be having fun in the process. After completion you will be able to program in Java, in addition to being able to use Greenfoot and Java libraries. With these skills, you will be able to quickly learn other (Object Oriented) programming languages. You will also learn how to use and adapt existing code where nec- essary. Re-use of existing code is one of Java’s strengths, because it allows you to make more complex programs in less time.

Programming

You will program in the Java language. For the assignments we will use the Greenfoot programming environment. This is an environment that allows you to write Java code without first having to learn (the theory of) Java in full-depth. In such a manner you can gradually learn Java while you’re actually using it to make stuff. You will learn the basic building blocks that are used for algorithms and programs.

Setting

Figure 1: Mimi the Dodo

This is Mimi, our Dodo. A Dodo (a bird which is now extinct) was never very intelligent. At first you will teach the Dodo simple tasks, like walking and turning. Throughout the course, you will teach the Dodo to complete more complex tasks, such as independently walking through any given maze. One of the final tasks is a competition with your classmates: who can make the smartest Dodo?

Computational Thinking

Computational thinking involves solving problems, designing systems, and understanding human be- havior. It’s not about trying to get humans to think like computers; it is a way humans solve problems.

Thinking like a computer scientist means more than being able to program a computer. It requires problem solving.

If you want to learn how to play chess, you have to know the rules. These rules tell you what you can and what you can’t do. But if you want to play chess well and enjoy playing the game, then merely knowing the rules is not enough. You also have to learn what a good move is. On internet you can find numerous Java tutorials and manuals. Those teach you the rules, but little about how to write a program well. In this course you will learn how to systematically deal with a programming task. You will learn to analyze problems and develop an appropriate solution in a structured and organized manner. The goal is to teach you to program well, and let you enjoy doing so.

Goals

The course is divided into several assignments. This assignment’s goals are:

• To learn how to make code modifications in a structured manner;

• Become acquainted with the Greenfoot environment.

(4)

Learning objectives

After completing this assignment, you will be able to:

• find your way around the Greenfoot programming environment;

• invoke methods and analyze their effect;

• in your own words, describe the difference between a mutator method and an accessor method;

• identify and list (inherited) methods of a class;

• use a class diagram to identify classes and subclasses;

• identify properties of an object’s state;

• describe what the types int, String, void, and boolean are;

• given a signature, identify a method’s result type and parameter(type)s;

• describe the relationship between an algorithm, a flowchart and program code;

• add JavaDoc comments to code;

• incrementally make code modifications and then compile and test;

• recognize and interpret (syntax) errors;

• print to a console.

Instructions

For this assignment you will need:

• Greenfoot: Instructions for installing and opening the Greenfoot environment are given further on;

• scenario ’DodoScenario1’: to be downloaded from the course website2.

Throughout the assignment you will also need to answer some questions. The following must be handed in:

• All flowcharts: use pencil and paper, or go to https://www.draw.io/;

• Your code: the file MyDodo . jav contains all your code and must be handed in;

• The reflection sheet: complete and hand it in.

You must discuss all other answers with a programming partner. Jot down a short answer on (the assignment) paper.

There are three types of challenges:

Recommended. Students who need more practice or with limited programming experience should complete all of these.

Mandatory. Everyone must complete these.

Excelling. More inquisitive tasks, designed for students who completed 2 star tasks and are ready for a bigger challenge.

Students who skip 1-star challenges should complete all 3-star challenges.

2http://course.cs.ru.nl/greenfoot/

(5)

Theory

Theory 1.1: Dodo’s world

Mimi belongs to the Dodo family. Here she is, facing East. Mimi lives in a (grid)world that is made-up of 12 by 12 squares. Her world is bounded, she can’t get out. Her sole goal in life is to lay and hatch eggs.

The picture shows the world’s coordinate system.

Figure 2: Mimi’s world

Mimi is a very well-behaved Dodo. She does exactly what she is told to do, and she always gives honest answers to your questions (she never lies). By calling methods, you can tell her to do something or ask her questions.

You can let Mimi do things, such as:

move move one square ahead hatchEgg hatch an egg

jump jump several squares ahead You can also ask Mimi a question, such as:

canMove Can you take a step forward?

getNrOfEggsHatched How many eggs have you hatched?

Theory 1.2: Objects

A world consists of objects (also known as class instances, or simply instances). By selecting new MyDodo ( ) you can create a new object of MyDodo. The world below shows one MyDodo object and three Egg objects.

(6)

Figure 3: Scenario with one MyDodo object and three Egg objects

In our assignments we have one lead actress, a MyDodo object. She is an instance of MyDodo. We will call her Mimi.

Theory 1.3: Algorithms

An algorithm is a very precisely defined set of instructions. Program code is an algorithm written specif- ically for a computer. It tells the computer exactly, step by step, what it should do. If a set of instructions has been described precisely enough, someone else should be able to follow the steps precisely as you meant it. For the same problem (initial situation) the instructions will lead to exactly the same outcome (final situation). It is similar to a recipe. The difference with a recipe is that an algorithm is more precise.

For example, a recipe might say ”stir until smooth”. However, each time you (or someone else) makes that dessert it may end up differently, one time being a bit smoother than the next. In an algorithm, it must be precisely clear what each step exactly means. The result must be exactly the same every time.

Theory 1.4: Methods

There are two types of methods, mutator methods and accessor methods, each with an own purpose:

Mutator methods

These are commands which make an object do something. It changes the state of an object. You can recognize a mutator method by its result: void. For example:

• void move ( ) changes the state of Dodo by moving it one cell ahead.

• void setDirection ( int new_direction ) changes the direction in which an object is facing.

Accessor methods

These are questions that provide information about (the state of) an object. For example:

• int getNrOfEggsHatched ( ) which returns an int (an integer, or whole number) indicating how many eggs Mimi has hatched.

• boolean canMove ( ) which returns a boolean (either true or false), indicating whether Mimi can take a step forwards or not.

Accessor methods only provide information about an object, they don’t do anything with an object: the object’s state remains unchanged (for example, Dodo doesn’t also move to another position).

(7)

Theory 1.5: Classes and inheritance

Every object belongs to a class. As such, Mimi is an instance of the MyDodo class. In the class diagram you can see that MyDodo belongs to the Dodo family. In Greenfoot, the class diagram is shown on the right-hand side of the screen. Have a look at figure 4. The arrow in the diagram shows an ’is-a’ relation- ship: MyDodo ’is-a’ Dodo. So, MyDodo belongs to the class Dodo.

Figure 4: Class diagram

MyDodo’s methods

Mimi is a MyDodo. Mimi has methods that you can call. By right-clicking on Mimi you can see what a MyDodo(and thus Mimi) can do. For example the move ( ) method.

Dodo’s methods

But Mimi (our MyDodo) is capable of doing much more. There are things that all Dodos, in general, can do. Mimi is a Dodo, so of course she can also do all the the things that Dodo’s can do too (and much more)!

Right-click on Mimi (in the world). At the top of the list you see ’inherited from Dodo’. If you click on that, then more methods will appear, such as layEgg ( ). These are methods which belong to the class Dodo, things that all Dodos can do. Because MyDodo is a Dodo (see the class diagram in figure 4), Dodo inherits (or gets) all these Dodo methods too. So, because MyDodo is a subclass of Dodo, a MyDodo so can perform all Dodo methods (in addition to its own MyDodo methods).

Inheritance

The fact that MyDodo can ’borrow’ methods from her superclass ’Dodo’ is called inheritance. By using inheritance, a new class can be introduced as an extension of an existing class. An instance of a sub- class can use all the methods from its superclass. In such a situation, the existing class is called the super class, and the extended class is called the subclass. Because MyDodo a subclass of Dodo, a MyDodo can execute methods from both the Dodo class as well as its own MyDodo class.

Example of a class diagram

Figure 5: Pet class diagram

The class diagram in 5 shows that Cats and Dogs are subclasses of PetAnimal.

• Every PetAnimal can sleep () and eat () , thus so can Cats and Dogs.

• A Cat can meow () . This method is specific to only Cats.

(8)

Theory 1.6: The state of an object

You can place different objects in the world, such as a Dodo and an egg. You can also place several objects of the same class in the world at the same time. In the picture below you see three objects of the Eggclass and one of the MyDodo class.

Figure 6: A world with several objects

All objects of the same class have the same methods, and thus have the same behavior. The three objects of Egg look identical and can do exactly the same things. Yet, they are different objects, or instances.

Every object has its own state. States are made up of characteristics such as coordinates or appear- ance. To view the state of an object, right-click on the object and then choose ’Inspect’. The following example shows the state of an Egg-object with coordinates (1,1) and one with coordinates (2,2).

Figure 7: States of two Egg-objects

Just like you’re different from the person sitting next to you, even though you are both people. The mere fact that you are each sitting on different chairs or had something different for breakfast, makes you different. The same is true in the Greenfoot world. Every object has its own state.

Theory 1.7: Parameters and results Results

In section 1.4 we saw that accessor methods give information about an object’s state (they answers questions). Such an answer is called the result of a method. For example, int getNrOfEggsHatched ( ) has an int (whole number) as its result.

Parameters

A method can also be given a certain value. This value, called a parameter, gives the method more information about a particular task. A method can have 0 or more parameters. Examples:

• void jump ( int distance ) has one parameter, distance, which tells the method how far it must jump. We can also tell that distance is a whole number, an int. By calling jump (3); Mimi will move forward 3 cells. By calling jump (5); Mimi will move forward 5 cells. The method jump needs this additional information in order to work. Otherwise, it would not know how many cells Mimi must move.

• void move ( ) has no parameters.

• void setDirection ( int new_direction ) has one parameter, an int new_direction which tells the method which direction to turn the object towards.

(9)

Types

Parameters and results have a type. The type indicates which sorts of values a parameter or result must have. Examples of different types are:

Type Meaning Example

int a whole number 2

boolean ’true’ or ’false’ true

String text enclosed in quote marks ”I lost my pen.”

List list [1,2,3]

A class can also be a type, such as a List of Eggs. It is not possible to call void jump ( int distance ) with no parameters because this method requires an int as a parameter.

Theory 1.8: Signatures

By looking at the signature of a method, you can see which parameters, parameter types and result types belong to the method.

• Method name: the method’s name is indicated in front of the first parenthesis. In this example:

jump.

• Parameter: the parameters that the method requires are indicated in between the parentheses ’(’

and ’)’. In this example: distance.

• Parameter type: the parameter’s type (such as int, boolean, or String) is indicated in front of the parameter’s name. In this example: int.

• Result type: the result’s type (such as int, boolean, void) is indicated in front of the method’s name. In this example the result type is void. This method doesn’t return anything (it is a mutator method).

• Method’s signature: together, all of the components above are called the signature. In this example:

public void jump ( int distance ). (the meaning of public will be explained later)

Figure 8: Signature of a method For the example above:

Method name jump

Parameter distance

Parameter type int

Result type void

Method’s signature public void jump ( int distance )

The types in the signature indicate which types of values a parameter or result must have.

(10)

Theory 1.9: Reading flowchart and code

An algorithm can be visually represented in a flowchart. This helps maintain overview, in turn making it easier to write, read and analyse code.

As an example we will look at the algorithm of MyDodo’s move ( ) method. We have already had a look at this method in challenge 1.1.4.

Figure 9: Flowchart and corresponding code

Figure 10: Flowchart and corresponding code

The flowchart explained

• Method name: move. The name can be found in the top-left corner.

• Initial and final situations are described in the note blocks in the top-right and bottom-right cor- ners.

• You begin at ’Start’ at the top.

• Body: this is the part between the ’Start’ and ’End’ and describes what the method actually does.

In this example:

Follow the arrow to the diamond.

The diamond means a decision (selection) is made, depending on the outcome of ’canMove?’

another path can be followed, namely:

* If ’canMove?’ is ’False’, then the arrow to the left is followed.

(11)

* If ’canMove?’ is ’True’, then the arrow to the right is followed.

This behavior is consistent with that of an if .. then .. else statement in the code.

In the case of a rectangle, a method is called. So, depending on which arrow has been followed the ’move’ or the ’turnRight’ method will be executed.

• When the ’End’ is reached, then the move method is finished.

The code explained

• Comment: the text in between /** and */ (shown in blue text in the Greenfoot editor) are com- ments. The compiler doesn’t do anything with this. Programmers write comments in their code to help others understand their programs. The initial and final situations are described here. For comments in the code that fit on just one line, use //.

• Signature: this is public void move ( ).

• Access modifier: public. What this means and which other possibilities there are, will be ex- plained later.

• Method name: move.

• Result type: void. What the method returns. This mutator method returns void which means it makes the object do something (as opposed to an accessor method which yields information about the object’s state) (See theory 1.4).

• Body: this is the part between the first curly bracket ’{’ and its corresponding curly bracket ’}’: what the method actually does.

In this example you see a conditional expression: the if .. then .. else in the move ( ). It works like this:

The condition is stated in between the parentheses ’(’ and ’)’. Firstly, the condition canMove is checked.

* If the condition is true, then the code directly following the condition is executed. Thus, step( ) is executed and Dodo takes a step.

* If the condition is false, then the code after the else is executed. Thus, an error message with the text ”I’m stuck” is shown.

Theory 1.10: Java Documentation

Each method should have comments clarifying what the code does. In Java this is called JavaDoc (’Java Documentation’). Documenting your codes helps others (and yourself) understand and re-use code.

Writing Java Documentation

In Java there are some standard agreements on how to comment code (see figure 11 for an example):

• Each method has comments (globally) describing what the method does.

• Each method explains the initial and final situation.

• Comments are started by /** and ended by */.

• For comments not longer than one line can, you can use // followed by the comment.

• @param indicates which parameters the method receives.

(12)

• @return indicates what the method returns.

Figure 11: Comments belonging to the jump method

Viewing Java Documentation

To view your code’s Java Documentation follow the following steps:

1. Open the code in the editor.

2. At the top-right of the screen, select ’Documentation’ instead of ’Source Code’. (See figure 12)

Figure 12: Selecting Java documentation instead of Source Code

Theory 1.11: Modifying, compiling and testing programs

To get Mimi to do more exciting things, you must write your own new methods. Obviously, you must first learn to read code before you can write code. Also, you should be able to describe which changes you want to make, after which you can actually make modifications to existing code.

Modifications

Always make changes incrementally. A typo can be introduced easily, whilst detecting it could be more troublesome. It is a good idea to compile, run and test every (small) change to the code so that you can quickly locate any mistakes. After each code change:

1. Compile: Press the Compile button on the top-left of the screen.

(13)

Figure 13: The compile button

2. Execute: Call the method by right-clicking on Mimi and then choosing the method.

Figure 14: Executing a method by right-clicking on Mimi in the world

3. Test: Check if the method does what you expect. Compare the initial and final situations.

Work in a structured manner

Make a habit of always following these steps after every code change. That way, if you make a mis- take, you can quickly find what the problem is. If you make many changes in one go without testing in between, then debugging (detecting errors in your code) can become a time-consuming and very frustrating task!

Theory 1.12: Naming conventions

Naming conventions

Methods and parameters have names. In Java, there are general conventions (or agreements) on how to choose a name. By following these conventions, your code becomes easier to read and understand for others.

A method’s name:

• is meaningful: it is consistent with what the method does

(14)

• is in the form of a command: it consists of one or more verbs

• consists of letters and numbers: it does not consist of spaces, commas, or other ”strange” charac- ters (with the exception of ’ ’)

• is written in lowerCaseCamel: starts with a lowercase letter, and each subsequent word starts with a capital letter

• for example: canMove A parameter’s name:

• is meaningful: it is consistent with what the parameter means

• consists of one or more nouns

• consists of letters and numbers: it does not consist of spaces, commas, or other ”strange” charac- ters (with the exception of ’ ’)

• is written in lowerCaseCamel: starts with a lowercase letter, and each subsequent word starts with a capital letter

• for example: nrOfEggs

See http://google-styleguide.googlecode.com/svn/trunk/javaguide.html for a complete overview of style and naming conventions.

Theory 1.13: Errors Syntax errors

If you type in something which the compiler does not understand, this is called a syntax error. Some common mistakes are:

Mistake Compiler error message

missing ’;’ at the end of the line ’;’ expected missing ’( )’ in the header ’(’ expected missing ’{’ at beginning of body ’;’ expected

missing ’}’ at end of body illegal start of expression

missing ’}’ at end of class reached end of file when parsing missing ’( )’ in method call not a statement

typo (watch out for capital/lowercase) cannot find symbol wrong parameter type used incompatible types

no parameter used method cannot be applied to given types wrong return type incompatible types: unexpected return value

wrong type used cannot find symbol

Logical errors

Besides syntax errors, there are also other types of programming errors. The compiler will not complain, but the program does not do what is expected. This is called a logical error. Such an error can be very difficult to find, and can be very frustrating. Searching for such an error is called debugging. Because prevention is beter than curing, we will discuss good programming practices in the next assignment.

By using a structured approach to programming you can significantly reduce the chance of these types of errors slipping into your code.

(15)

Theory 1.14: Printing to the console

When debugging, it can be useful to print values or statements to determine where errors are located. To

make a console window appear with text you can use the following Java method: System . out . println ( String ); . The following example shows the output in the console and its corresponding code.

Figure 15: Printing in the console

Depending on what needs to be printed, the println method is called with different arguments:

• Place text in between quotation marks ’ ’ and ’ ’.

• To show the value of a variable (such as an integer, double or string), the quotation marks are not needed, just use the variable name.

• Combine texts and variables using ’ + ’.

Note:

For more information about the Java println method, have a look at: https://docs.oracle.com/javase/

7/docs/api/java/io/PrintStream.html#println(java.lang.String).

(16)

Challenges

Challenge 1.1: Getting started with Greenfoot Starting Greenfoot

We’re going to play around with Mimi in the Greenfoot environment. To do this, you must download and install Greenfoot 3.0.4 (if it has not already been done for you, you can download it at ) and open the given scenario.

Download and install Greenfoot Version 3.0.4 (if not already done):

• Go to http://www.greenfoot.org/download.

• Download the appropriate version for your operating system and follow the instructions for installation.

Choose a folder:

• Decide where you will save all your work. If you wish, you can use a USB-stick for this.

Download:

• Go to the course page and download the scenario files belonging to this assignment: Copy the given exe-file with initial scenario to the folder which you have chosen.

• Unpack the scenario at that location, just by clicking on the exe-file.

Open the Greenfoot environment:

• Double click on the Greenfoot.exe file. The programming environment should start now.

Open the scenario:

• Select ’Scenario’ in the main menu, and then ’Open’.

• Navigate to the ’DodoScenario1’ scenario (which you downloaden en unzipped) and chose

’Open’.

Rename the scenario:

• In the Greenfoot menu at the top of the screen, select ’Scenario’ and then ’Save As ...’.

• Check that the window opens in the folder where you want to save your work.

• Choose a file name containing your own name(s) and assignment number, for example:

Asgmt1_John. You should see the following:

(17)

Figure 16: What you see when you open the ’DodoScenario1’ scenario

Please read Theory 1.1: Dodo’s world.

Please read Theory 1.2: Objects.

Challenge 1.2: Creating objects

We’re going to make the scenario as shown in figure 3:

a) Right-click on MyDodo, on the far right-hand of the screen.

b) Select new MyDodo ( ) to create a new MyDodo object.

c) Drag the object, our MyDodo called Mimi, to a random position in the world.

d) In the same manner, place three BlueEggs in the world. Tip: hold down the Shift button on your keyboard to place multiple blue eggs.

Please read Theory 1.3: Algorithms.

Please read Theory 1.4: Methods.

Challenge 1.3: Exploring the accessor method

By right-clicking on Mimi, you can see a list of all the things she can do (in other words, which methods you can call). By using some of those methods (called accessor methods) you can get Mimi to answer questions about herself.

a) Drag Mimi into the middle of the world. Right-click on Mimi, and call the boolean canMove ( ) method. A dialogue box appears, as shown below. The method returns true.

(18)

Figure 17: Dialogue box for canMove ( )

b) Can you move Mimi to another location so that boolean canMove ( ) returns a different result than true?

c) What do you think boolean means?

d) Besides returning a result, let’s have a look at what such an accessor method does:

i. Describe the current situation: Where is Mimi and what direction is she facing? Are there any eggs?

ii. Call the method int getNrOfEggsHatched ( ).

iii. Does calling this method change the situation in the world?

e) What result did int getNrOfEggsHatched ( ) give? What does int mean?

f) Can you create a situation in which the method int getNrOfEggsHatched ( ) returns the value 3?

Tip: first place eggs in the world and then call hatchEgg ( ).

You have now seen that an accessor method returns information such as int or boolean, but shouldn’t change the situation or state of an object.

Challenge 1.4: Exploring the mutator method

Our MyDodo has been programmed to do several things. You can let her do things (give her commands) by calling her mutator methods.

a) Right-click on Mimi. You will see a list of all the things Mimi can do (in other words, which meth- ods you can call), for example move ( ), and hatchEgg ( ). Name one other method which makes Mimi do something.

b) Drag Mimi to the centre of the world. Call Mimi’s method void move ( ). Can you describe what the method does?

i. Drag Mimi to the edge of the world, facing outwards. Call Mimi’s method void move ( ) again.

What happens now? Tip: to get rid of the pop-up dialogue, click either ’Reset’ or ’Run.’

ii. Using what you have just seen, match A, B and C in the flowchart in figure 18 to its correspond- ing code.

(19)

Figure 18: Flowchart and code for MyDodo’s move ( ) method

Please read Theory 1.5: Classes and inheritance.

Challenge 1.5: Inheritance

We will now have a look at the methods which a MyDodo inherits from the Dodo family.

a) Mimi is a MyDodo. All MyDodos are Dodos. Have a look at the class diagram on the right of the screen.

Which other ’is-a’ relationships do you see? Name at least two.

b) Mimi (who is a MyDodo), can do everything a Dodo can do. Right-click on Mimi (in the world). Click on ’inherited from Dodo’. More methods appear, such as layEgg ( ). Check that Mimi can execute the layEgg () .

c) Name two other methods which Mimi the MyDodo inherits from the Dodo class.

d) In addition to Dodo methods, Mimi can do a few specific things that only MyDodo can do. Find a method which only MyDodo’s have (and Dodos don’t).

We have now seen that Mimi (and all other MyDodos) inherit and thus can execute all Dodo methods.

Please read Theory 1.6: The state of an object.

Challenge 1.6: States

Every object has a state. We will now have a look at how you can ’Inspect’ the states of objects.

a) Drag Mimi into the world. Right-click on Mimi and select ’Inspect’. What are her (int x and int y) coordinates?

b) Investigate what the coordinates are at each of the corners. Draw in the coordinates in figure 19.

The top-left corner has already been done for you.

(20)

Figure 19: Coordinates in the world

Please read Theory 1.7: Parameters and results.

Please read Theory 1.8: Signatures.

Challenge 1.7: Calling Accessor Methods

In challenge 1.6 we saw that you can use ’Inspect’ to get information about Mimi’s state. Accessor meth- ods are used to return this information. Let’s have a look at how this works.

a) Right-click on Mimi.

b) Which Dodo class methods return the coordinates of an object?

Challenge 1.8: Using Parameters

Let’s have a look at a few examples of methods with parameters.

a) Place Mimi somewhere in the middle of the world. Right-click on Mimi. Call the method jump ( int distance ).

This method requires an int (whole number) as a parameter so that it knows how far (distance) Mimi must jump. Type in a small number and see what happens.

b) Call the method jump ( int distance ) again. This time use a large number, such as 20, as the pa- rameter. What happens? Can you explain why?

c) What happens when you type something in that is not an int (whole number), such as 2.5? What error message do you get? What does this mean? (Tip: have a look at section Theory 1.13)

d) If you type in a word as a parameter, instead of a number, you get an error message like in figure 20. Why does the error say something about a String?

Figure 20: Error message when using text as a parameter

(21)

Please read Theory 1.9: Reading flowchart and code.

Challenge 1.9: Reading a flowchart and its corresponding code

We will now look at the canLayEgg ( ) method. Mimi can only lay an egg if there isn’t an egg there already.

a) Open MyDodo’s code in the editor: Right-click MyDodo in the class diagram and select ’Open editor’.

b) Find the canLayEgg ( ) method. Tip: use Ctrl+F.

c) Have a look at the code for the boolean canLayEgg ( ) method in figure 22. The flowchart in figure 21 on the left visualizes the algorithm. Fill in the missing gaps for A,B,C,D (in the flowchart) and E (in the code).

d) Remove the comments in front of the code.

e) In the code fill in E.

f) Test your method.

(22)

Figure 21: Flowchart for canLayEgg ( ) method

Figure 22: Code for canLayEgg ( ) method

Please read Theory 1.10: Java Documentation.

Please read Theory 1.11: Modifying, compiling and testing programs.

Please read Theory 1.12: Naming conventions.

Challenge 1.10: Adding a new method turn180()

We are now going to add a new method to MyDodo which makes Mimi turn 180 around.

Figure 23: Flowchart and code for turn180

a) Have a look at the flowchart and its code. Fill in the missing gaps for A and B.

b) Open the MyDodo class code in the editor.

c) Write the code for the method turn180.

d) Compile the code by pressing on the ’Compile’ button in the top-left part of the screen (see figure 24).

(23)

Figure 24: Compile button If necessary fix any mistakes.

e) Call your new method by right-clicking on Mimi and selecting void turn180 ( ). Test if it works as expected. Also test if the other methods still work correctly. In other words, check if the program as a whole still works as expected.

f) Add comments above the turn180 ( ) method explaining what the method does, and what the initial and final situations are. Tip: Theory 1.10 explains how to add JavaDoc comments to code.

Please read Theory 1.13: Errors.

Challenge 1.11: Error messages

The compiler is very picky. If you make a mistake in the code or forget something, the compiler will complain. It’s useful to be able to recognize some common mistakes and error messages so that you can easily find the problem and fix it. Let’s have a look at a few.

a) Open the MyDodo class in the editor and find your method turn180 ( ).

b) For each of the following, make the changes described, compile, and match the error message to the error in the code. Then fix the error in the code again.

i. Delete a semi-colon ’;’ behind turnRight ( );

ii. Change the spelling of turn180 ( ) iii. Change turn180 ( ) into turn180 (5)

iv. Remove the ’{ ’ after turn180 ( ) v. Remove the ’)’ in turn180 ( ) vi. Remove the ’( )’ in turn180 ( )

Problem Error message

’;’ expected

’(’ expected

method cannot be applied to given types invalid method declaration

’)’ expected

cannot find symbol

3. Fix the errors and test if the program still works as expected.

Please read Theory 1.14: Printing to the console.

Challenge 1.12: Printing text to the console

Printing to the console (a separate window) can be useful for testing.

a) Find the code for your turn180 ( ) method.

(24)

b) Add the following print-to-console statement near the end of the method:

System. out . println (’’I just turned 180 degrees’’ );

c) Execute your method by right-clicking on Mimi and calling turn180. Note: the console window may be hidden behind one of your other windows.

You have now seen how to write code to print a text.

Challenge 1.13: Printing variables to the console

Printing to the console (a separate window) can be useful for testing.

a) Find the code for MyDodo’s jump ( ).

b) The code doesn’t correspond to the flowchart in figure 25. The difference is that the flowchart shows a print-to-console statement in the repeat-block.

Figure 25: Example flowchart for printing text to the console

c) Use System . out . println ("moved " + nrStepsTaken ); to add the print-to-console statement in the appropriate place in the code.

d) Execute your method by right-clicking on Mimi and calling jump. Note: the console window may be hidden behind one of your other windows.

e) Test your method using several different values.

You have now seen how to write code to print both text and a variable to a console.

Challenge 1.14: Printing coordinates to the console

The mission is:

”Mimi walks across her row printing her coordinates to the console at each step.”

(25)

a) Add the code for printing the coordinates.

b) Test your method. Does it also print the last coordinate?

c) Fix the flowchart and code. Also add (JavaDoc) comments to your code.

You have now written your own method and used a print statement to test if it works appropriately.

(26)

Reflection

In this assignment you have become acquainted with Greenfoot. You have also been introduced to code.

You adjusted code yourself, and practiced compiling and testing each small change that you made. One of the most important steps in becoming good at anything is to evaluate and reflect on what you did and how it went. Take one of the challenges in mind that you are proud of to reflect on.

Result

I know my solution works because ...

I am proud of my solution because ...

I could improve my solution by ...

Method

My approach was good because ...

What I could do better next time is ...

Fill the following table with smileys

indicating how things went. I can do it

I did it a bit but didn’t fully get it I didn’t get it at all

I can find my way around the Greenfoot environment

I can explore which methods an object has and call (invoke) these

I can explain the relationship between an algorithm, its flowchart and its code

Given a method, I can find the code in the Greenfoot editor

I can incrementally make changes to code

I can add a method, compile, run and test

I can recognize error messages

(27)

Diagnostic Test

Here are sample answers to the questions in the diagnostic test:

1. Which of the following is an int (more than one answer is possible):

(a) getNrOfEggsHatched () (b) 4

(c) 3.2 (d) four (e) -3

(f) 0 (g) False 2. True or false?

(a) boolean canMove () is an accessor method;

(b) move () is an accessor method;

(c) jump ( int distance ) is a mutator method.

3. Explain in your own words what a result type is. Give an example.

4. Match up numbers 1 through 6 in the flowchart in figure 26 with their corresponding parts of code.

Figure 26: Code for MyDodo’s move () method 5. Name a method that belongs to MyDodo but not to Dodo.

6. Have a look at the following class diagram:

Figure 27: Class diagram

(28)

(a) Fill the class diagram with the following class names:

• Kangaroo

• Lion

• ZooAnimal

(b) Add the following methods to the corresponding superclass or subclasses:

• hop ( )

• sleep ( )

• roar ( )

• eatMeat ( )

(c) Name all the methods which a Kangaroo can use.

7. What are the coordinates in the bottom-left corner?

8. Complete the table below.

Method Result type Parameter type Belongs to class To be used by object

getNrOfEggsHatched () none MyDodo MyDodo

canMove() boolean

jump()

layEgg() void

turnLeft() Dodo and MyDodo

canMove() MyDodo

getX()

9. Below are some names for a method which returns the number of eggs found. According to the naming conventions for methods names, which one is the best?

(a) nrOfEggs (b) nrOfEggsFound (c) setNrOfEggsFound (d) getNrOfEggsFound

10. Below are some names for a method. According to the naming conventions for method names, which one is the best?

(a) walk_to_egg (b) eggWalker (c) WalkToEgg (d) walkToEgg (e) WALK_TO_EGG

11. Below are some names for a parameter indicating the number of eggs. According to the naming conventions for parameter names, which one is the best?

(a) nr_of_eggs (b) EggCounter (c) nrOfEggs (d) eggs (e) NR_OF_EGGS

(29)

12. Here is code for a new method:

public A moveDown ( ){

turnRight( ) ; move( ) ; B

}

The corresponding flowchart is:

Figure 28: Flowchart for moveDown () (a) Fill in A, B, C, D, E, F and G in the code and the flowchart.

(b) What is the method’s signature?

Saving and Handing in

You have just finished the assignment. Save your work! You will need this for future assignments. In the Greenfoot menu at the top of the screen, select ’Scenario’ and then ’Save’. You now have all the scenario components in one folder. The folder has the name you chose when you selected ’Save As ...’.

Handing in

Hand in the following:

• Your name(s): you and your partner;

• Your code: The java file MyDodo . jav;

• Flowcharts: paste (photo’s of) your flowcharts in a Word document;

• The reflection sheet: complete and hand it in.

Referenties

GERELATEERDE DOCUMENTEN

Mr Ostler, fascinated by ancient uses of language, wanted to write a different sort of book but was persuaded by his publisher to play up the English angle.. The core arguments

b) Replace the circled code by a call of stepBack, according to the following flowchart:.. Figure 18: Flowchart for grainAhead using submethod stepBack c) Test your program... d) Can

b) Draw the corresponding flowchart. Return the number of eggs found as a result. Tip: The return is the very last statement that can be called. Mimi must thus first go back to

Mais, c’est précisément dans ce genre de contrôle que l’introduction d’un niveau de sécurité devient très délicat étant donné qu’il est impossible de

You could forge crucial documents like Ossian's poems and the Czech Manuscripts, or you could even invent a druid tradition for the Welsh, which everybody knew was a

Procentueel lijkt het dan wel alsof de Volkskrant meer aandacht voor het privéleven van Beatrix heeft, maar de cijfers tonen duidelijk aan dat De Telegraaf veel meer foto’s van

In verschillende sleuven kon vastgesteld worden dat de fundering van de westgevel van de bestaande vleugel B in oorsprong toebehoorde aan een ver- dwenen dwarsvleugel: de

In Brecht konden vijf greppels niet gedateerd worden, de andere greppels zijn sporen die onder het plaggendek werden aangetroffen en aldus uit de Late Middeleeuwen of vroeger