29
Assignment 1: Meet Dodo Algorithmic Thinking and Structured Programming (in Greenfoot) © Renske Smetsers-Weeda & Sjaak Smetsers Contents Introduction Learning objectives Instructions Theory . Dodo’s world ..................................................... . Objects ........................................................ . Algorithms ..................................................... . Methods ....................................................... . Classes and inheritance ............................................. . The state of an object ............................................... . Parameters and results .............................................. . Signatures ...................................................... . Reading owchart and code ........................................... . Java Documentation ............................................... . Modifying, compiling and testing programs ................................. . Naming conventions ............................................... . Errors ........................................................ . Printing to the console ............................................. Challenges . Getting started with Greenfoot ......................................... . Creating objects .................................................. . Exploring the accessor method ......................................... . Exploring the mutator method ......................................... . Inheritance ..................................................... . States ......................................................... . Calling Accessor Methods ............................................ . Using Parameters ................................................. Licensed under the Creative Commons Attribution . license: https://creativecommons.org/licenses/by/4.0/

Assignment 1: Meet Dodo - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment1... · Assignment 1: Meet Dodo ... Figure 1: Mimi the Dodo This is Mimi,

Embed Size (px)

Citation preview

Page 1: Assignment 1: Meet Dodo - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment1... · Assignment 1: Meet Dodo ... Figure 1: Mimi the Dodo This is Mimi,

Assignment 1: Meet Dodo

Algorithmic Thinking and Structured Programming (in Greenfoot)© 2017 Renske Smetsers-Weeda & Sjaak Smetsers1

ContentsIntroduction 1

Learning objectives 2

Instructions 2

Theory 31.1 Dodo’s world . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.2 Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.3 Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41.4 Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41.5 Classes and inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41.6 The state of an object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51.7 Parameters and results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61.8 Signatures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71.9 Reading flowchart and code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71.10 Java Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91.11 Modifying, compiling and testing programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101.12 Naming conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111.13 Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121.14 Printing to the console . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Challenges 141.1 Getting started with Greenfoot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141.2 Creating objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151.3 Exploring the accessor method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151.4 Exploring the mutator method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161.5 Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171.6 States . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171.7 Calling Accessor Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181.8 Using Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

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

Page 2: Assignment 1: Meet Dodo - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment1... · Assignment 1: Meet Dodo ... Figure 1: Mimi the Dodo This is Mimi,

Meet Dodo Assignment 1

1.9 Reading a flowchart and its corresponding code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191.10 Adding a new method turn180() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201.11 Error messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211.12 Printing text to the console . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211.13 Printing variables to the console . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221.14 Printing coordinates to the console . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22Reflection 24

Diagnostic Test 25

Saving and Handing in 27

Algorithmic thinking and structured programming (in Greenfoot) 2

Page 3: Assignment 1: Meet Dodo - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment1... · Assignment 1: Meet Dodo ... Figure 1: Mimi the Dodo This is Mimi,

Meet Dodo Assignment 1

IntroductionIn this series of assignments, Algorithmic Thinking and Structured Programming (in Greenfoot), youwill 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 beingable to use Greenfoot and Java libraries. With these skills, you will be able to quickly learn other (ObjectOriented) 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 complexprograms in less time.ProgrammingYou will program in the Java language. For the assignments we will use the Greenfoot programmingenvironment. This is an environment that allows you to write Java code without first having to learn (thetheory of) Java in full-depth. In such a manner you can gradually learn Java while you’re actually usingit to make stuff. You will learn the basic building blocks that are used for algorithms and programs.Setting

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

Computational ThinkingComputational 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 requiresproblem solving.If you want to learn how to play chess, you have to know the rules. These rules tell you what youcan and what you can’t do. But if you want to play chess well and enjoy playing the game, then merelyknowing the rules is not enough. You also have to learn what a good move is. On internet you can findnumerous Java tutorials and manuals. Those teach you the rules, but little about how to write a programwell. In this course you will learn how to systematically deal with a programming task. You will learnto analyze problems and develop an appropriate solution in a structured and organized manner. Thegoal is to teach you to program well, and let you enjoy doing so.GoalsThe 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.

Algorithmic thinking and structured programming (in Greenfoot) 1

Page 4: Assignment 1: Meet Dodo - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment1... · Assignment 1: Meet Dodo ... Figure 1: Mimi the Dodo This is Mimi,

Meet Dodo Assignment 1

Learning objectivesAfter 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.

InstructionsFor 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 handedin:• 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 (theassignment) paper.

There are three types of challenges:Recommended. Students who need more practice or with limited programming experienceshould complete all of these.Mandatory. Everyone must complete these.Excelling. More inquisitive tasks, designed for students who completed 2 star tasks and areready for a bigger challenge.Students who skip 1-star challenges should complete all 3-star challenges.

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

Algorithmic thinking and structured programming (in Greenfoot) 2

Page 5: Assignment 1: Meet Dodo - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment1... · Assignment 1: Meet Dodo ... Figure 1: Mimi the Dodo This is Mimi,

Meet Dodo Assignment 1

Theory

Theory 1.1: Dodo’s worldMimi belongs to the Dodo family. Here she is, facing East. Mimi lives in a (grid)world that is made-upof 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 worldMimi is a very well-behaved Dodo. She does exactly what she is told to do, and she always giveshonest answers to your questions (she never lies). By calling methods, you can tell her to do somethingor ask her questions.You can let Mimi do things, such as:

move move one square aheadhatchEgg hatch an eggjump 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: ObjectsA 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.

Algorithmic thinking and structured programming (in Greenfoot) 3

Page 6: Assignment 1: Meet Dodo - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment1... · Assignment 1: Meet Dodo ... Figure 1: Mimi the Dodo This is Mimi,

Meet Dodo Assignment 1

Figure 3: Scenario with one MyDodo object and three Egg objectsIn our assignments we have one lead actress, a MyDodo object. She is an instance of MyDodo . We willcall her Mimi.

Theory 1.3: AlgorithmsAn 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 instructionshas been described precisely enough, someone else should be able to follow the steps precisely as youmeant 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) makesthat dessert it may end up differently, one time being a bit smoother than the next. In an algorithm, itmust be precisely clear what each step exactly means. The result must be exactly the same every time.Theory 1.4: MethodsThere are two types of methods, mutator methods and accessor methods, each with an own purpose:Mutator methodsThese are commands which make an object do something. It changes the state of an object. You canrecognize 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 methodsThese 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 howmany eggs Mimi has hatched.• boolean canMove ( ) which returns a boolean (either true or false), indicating whether Mimi cantake a step forwards or not.

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

Algorithmic thinking and structured programming (in Greenfoot) 4

Page 7: Assignment 1: Meet Dodo - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment1... · Assignment 1: Meet Dodo ... Figure 1: Mimi the Dodo This is Mimi,

Meet Dodo Assignment 1

Theory 1.5: Classes and inheritanceEvery object belongs to a class. As such, Mimi is an instance of the MyDodo class. In the class diagramyou can see that MyDodo belongs to the Dodo family. In Greenfoot, the class diagram is shown on theright-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 diagramMyDodo’s methodsMimi is a MyDodo . Mimi has methods that you can call. By right-clicking on Mimi you can see what aMyDodo (and thus Mimi) can do. For example the move ( ) method.Dodo’s methodsBut Mimi (our MyDodo) is capable of doing much more. There are things that all Dodos, in general, cando. Mimi is a Dodo, so of course she can also do all the the things that Dodo’s can do too (and muchmore)!Right-click on Mimi (in the world). At the top of the list you see ’inherited from Dodo’. If you click onthat, then more methods will appear, such as layEgg ( ) . These are methods which belong to the classDodo, things that all Dodos can do. Because MyDodo is a Dodo (see the class diagram in figure 4), Dodoinherits (or gets) all these Dodo methods too. So, because MyDodo is a subclass of Dodo, a MyDodo so canperform all Dodo methods (in addition to its own MyDodo methods).InheritanceThe fact that MyDodo can ’borrow’ methods from her superclass ’Dodo’ is called inheritance. By usinginheritance, 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 thesuper class, and the extended class is called the subclass. Because MyDodo a subclass of Dodo, a MyDodocan execute methods from both the Dodo class as well as its own MyDodo class.Example of a class diagram

Figure 5: Pet class diagramThe 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.

Algorithmic thinking and structured programming (in Greenfoot) 5

Page 8: Assignment 1: Meet Dodo - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment1... · Assignment 1: Meet Dodo ... Figure 1: Mimi the Dodo This is Mimi,

Meet Dodo Assignment 1

Theory 1.6: The state of an objectYou can place different objects in the world, such as a Dodo and an egg. You can also place severalobjects of the same class in the world at the same time. In the picture below you see three objects of theEgg class and one of the MyDodo class.

Figure 6: A world with several objectsAll objects of the same class have the same methods, and thus have the same behavior. The threeobjects of Egg look identical and can do exactly the same things. Yet, they are different objects, orinstances.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 followingexample shows the state of an Egg-object with coordinates (1,1) and one with coordinates (2,2).

Figure 7: States of two Egg-objectsJust like you’re different from the person sitting next to you, even though you are both people. Themere fact that you are each sitting on different chairs or had something different for breakfast, makesyou different. The same is true in the Greenfoot world. Every object has its own state.

Theory 1.7: Parameters and results

ResultsIn section 1.4 we saw that accessor methods give information about an object’s state (they answersquestions). Such an answer is called the result of a method. For example, int getNrOfEggsHatched ( )has an int (whole number) as its result.ParametersA method can also be given a certain value. This value, called a parameter, gives the method moreinformation 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 mustjump. We can also tell that distance is a whole number, an int. By calling jump (3); Mimi willmove forward 3 cells. By calling jump (5); Mimi will move forward 5 cells. The method jump needsthis additional information in order to work. Otherwise, it would not know how many cells Mimimust move.• void move ( ) has no parameters.• void setDirection ( int new_direction ) has one parameter, an int new_direction which tellsthe method which direction to turn the object towards.

Algorithmic thinking and structured programming (in Greenfoot) 6

Page 9: Assignment 1: Meet Dodo - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment1... · Assignment 1: Meet Dodo ... Figure 1: Mimi the Dodo This is Mimi,

Meet Dodo Assignment 1

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

Type Meaning Exampleint a whole number 2boolean ’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: SignaturesBy looking at the signature of a method, you can see which parameters, parameter types and resulttypes 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 theparameter’s name. In this example: int.• Result type: the result’s type (such as int, boolean , void) is indicated in front of the method’sname. In this example the result type is void. This method doesn’t return anything (it is a mutatormethod).• 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 methodFor the example above:

Method name jumpParameter distanceParameter type intResult type voidMethod’s signature public void jump ( int distance )The types in the signature indicate which types of values a parameter or result must have.

Algorithmic thinking and structured programming (in Greenfoot) 7

Page 10: Assignment 1: Meet Dodo - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment1... · Assignment 1: Meet Dodo ... Figure 1: Mimi the Dodo This is Mimi,

Meet Dodo Assignment 1

Theory 1.9: Reading flowchart and codeAn algorithm can be visually represented in a flowchart. This helps maintain overview, in turn makingit 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 atthis method in challenge 1.1.4.

Figure 9: Flowchart and corresponding code

Figure 10: Flowchart and corresponding codeThe 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.

Algorithmic thinking and structured programming (in Greenfoot) 8

Page 11: Assignment 1: Meet Dodo - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment1... · Assignment 1: Meet Dodo ... Figure 1: Mimi the Dodo This is Mimi,

Meet Dodo Assignment 1

* 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 followedthe ’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 codeto help others understand their programs. The initial and final situations are described here. Forcomments 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 itmakes the object do something (as opposed to an accessor method which yields information aboutthe object’s state) (See theory 1.4).• Body: this is the part between the first curly bracket ’{’ and its corresponding curly bracket ’}’: whatthe method actually does.In this example you see a conditional expression: the if .. then .. else in the move ( ) . It workslike this:

– The condition is stated in between the parentheses ’(’ and ’)’. Firstly, the condition canMove ischecked.* 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 messagewith the text ”I’m stuck” is shown.

Theory 1.10: Java DocumentationEach method should have comments clarifying what the code does. In Java this is called JavaDoc (’JavaDocumentation’). Documenting your codes helps others (and yourself) understand and re-use code.Writing Java DocumentationIn 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.

Algorithmic thinking and structured programming (in Greenfoot) 9

Page 12: Assignment 1: Meet Dodo - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment1... · Assignment 1: Meet Dodo ... Figure 1: Mimi the Dodo This is Mimi,

Meet Dodo Assignment 1

• @return indicates what the method returns.

Figure 11: Comments belonging to the jump methodViewing Java DocumentationTo 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 programsTo get Mimi to do more exciting things, you must write your own new methods. Obviously, you mustfirst learn to read code before you can write code. Also, you should be able to describe which changesyou want to make, after which you can actually make modifications to existing code.ModificationsAlways make changes incrementally. A typo can be introduced easily, whilst detecting it could be moretroublesome. It is a good idea to compile, run and test every (small) change to the code so that you canquickly locate any mistakes. After each code change:

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

Algorithmic thinking and structured programming (in Greenfoot) 10

Page 13: Assignment 1: Meet Dodo - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment1... · Assignment 1: Meet Dodo ... Figure 1: Mimi the Dodo This is Mimi,

Meet Dodo Assignment 1

Figure 13: The compile button2. 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 world3. Test: Check if the method does what you expect. Compare the initial and final situations.

Work in a structured mannerMake 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 testingin between, then debugging (detecting errors in your code) can become a time-consuming and veryfrustrating task!Theory 1.12: Naming conventionsNaming conventions

Methods and parameters have names. In Java, there are general conventions (or agreements) on howto choose a name. By following these conventions, your code becomes easier to read and understandfor others.A method’s name:

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

Algorithmic thinking and structured programming (in Greenfoot) 11

Page 14: Assignment 1: Meet Dodo - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment1... · Assignment 1: Meet Dodo ... Figure 1: Mimi the Dodo This is Mimi,

Meet Dodo Assignment 1

• 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 witha 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 witha capital letter• for example: nrOfEggsSee http://google-styleguide.googlecode.com/svn/trunk/javaguide.html for a complete overviewof style and naming conventions.

Theory 1.13: Errors

Syntax errorsIf you type in something which the compiler does not understand, this is called a syntax error. Somecommon mistakes are:

Mistake Compiler error messagemissing ’;’ at the end of the line ’;’ expectedmissing ’( )’ in the header ’(’ expectedmissing ’{’ at beginning of body ’;’ expectedmissing ’}’ at end of body illegal start of expressionmissing ’}’ at end of class reached end of file when parsingmissing ’( )’ in method call not a statementtypo (watch out for capital/lowercase) cannot find symbolwrong parameter type used incompatible typesno parameter used method cannot be applied to given typeswrong return type incompatible types: unexpected return valuewrong type used cannot find symbolLogical errorsBesides 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 verydifficult to find, and can be very frustrating. Searching for such an error is called debugging. Becauseprevention 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 typesof errors slipping into your code.

Algorithmic thinking and structured programming (in Greenfoot) 12

Page 15: Assignment 1: Meet Dodo - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment1... · Assignment 1: Meet Dodo ... Figure 1: Mimi the Dodo This is Mimi,

Meet Dodo Assignment 1

Theory 1.14: Printing to the consoleWhen debugging, it can be useful to print values or statements to determine where errors are located. Tomake 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 consoleDepending 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 notneeded, 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).

Algorithmic thinking and structured programming (in Greenfoot) 13

Page 16: Assignment 1: Meet Dodo - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment1... · Assignment 1: Meet Dodo ... Figure 1: Mimi the Dodo This is Mimi,

Meet Dodo Assignment 1

Challenges

Challenge 1.1: Getting started with Greenfoot

Starting GreenfootWe’re going to play around with Mimi in the Greenfoot environment. To do this, you must download andinstall Greenfoot 3.0.4 (if it has not already been done for you, you can download it at ) and open thegiven 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 forinstallation.

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 thegiven 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:

Algorithmic thinking and structured programming (in Greenfoot) 14

Page 17: Assignment 1: Meet Dodo - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment1... · Assignment 1: Meet Dodo ... Figure 1: Mimi the Dodo This is Mimi,

Meet Dodo Assignment 1

Figure 16: What you see when you open the ’DodoScenario1’ scenarioPlease read Theory 1.1: Dodo’s world.

Please read Theory 1.2: Objects.

Challenge 1.2: Creating objectsWe’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 yourkeyboard to place multiple blue eggs.

Please read Theory 1.3: Algorithms.

Please read Theory 1.4: Methods.

Challenge 1.3: Exploring the accessor methodBy right-clicking on Mimi, you can see a list of all the things she can do (in other words, which methodsyou can call). By using some of those methods (called accessor methods) you can get Mimi to answerquestions 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.

Algorithmic thinking and structured programming (in Greenfoot) 15

Page 18: Assignment 1: Meet Dodo - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment1... · Assignment 1: Meet Dodo ... Figure 1: Mimi the Dodo This is Mimi,

Meet Dodo Assignment 1

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 anyeggs?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’tchange the situation or state of an object.Challenge 1.4: Exploring the mutator methodOur 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 makesMimi do something.b) Drag Mimi to the centre of the world. Call Mimi’s method void move ( ) . Can you describe whatthe 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.

Algorithmic thinking and structured programming (in Greenfoot) 16

Page 19: Assignment 1: Meet Dodo - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment1... · Assignment 1: Meet Dodo ... Figure 1: Mimi the Dodo This is Mimi,

Meet Dodo Assignment 1

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

Please read Theory 1.5: Classes and inheritance.

Challenge 1.5: InheritanceWe 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). Clickon ’inherited from Dodo’. More methods appear, such as layEgg ( ) . Check that Mimi can executethe 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 amethod 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: StatesEvery 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.

Algorithmic thinking and structured programming (in Greenfoot) 17

Page 20: Assignment 1: Meet Dodo - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment1... · Assignment 1: Meet Dodo ... Figure 1: Mimi the Dodo This is Mimi,

Meet Dodo Assignment 1

Figure 19: Coordinates in the worldPlease read Theory 1.7: Parameters and results.

Please read Theory 1.8: Signatures.

Challenge 1.7: Calling Accessor MethodsIn 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 ParametersLet’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? Whaterror 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 figure20. Why does the error say something about a String?

Figure 20: Error message when using text as a parameter

Algorithmic thinking and structured programming (in Greenfoot) 18

Page 21: Assignment 1: Meet Dodo - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment1... · Assignment 1: Meet Dodo ... Figure 1: Mimi the Dodo This is Mimi,

Meet Dodo Assignment 1

Please read Theory 1.9: Reading flowchart and code.

Challenge 1.9: Reading a flowchart and its corresponding codeWe will now look at the canLayEgg ( ) method. Mimi can only lay an egg if there isn’t an egg therealready.

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

Algorithmic thinking and structured programming (in Greenfoot) 19

Page 22: Assignment 1: Meet Dodo - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment1... · Assignment 1: Meet Dodo ... Figure 1: Mimi the Dodo This is Mimi,

Meet Dodo Assignment 1

Figure 21: Flowchart for canLayEgg ( ) method

Figure 22: Code for canLayEgg ( ) methodPlease 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 figure24).

Algorithmic thinking and structured programming (in Greenfoot) 20

Page 23: Assignment 1: Meet Dodo - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment1... · Assignment 1: Meet Dodo ... Figure 1: Mimi the Dodo This is Mimi,

Meet Dodo Assignment 1

Figure 24: Compile buttonIf necessary fix any mistakes.

e) Call your new method by right-clicking on Mimi and selecting void turn180 ( ) . Test if it works asexpected. Also test if the other methods still work correctly. In other words, check if the programas a whole still works as expected.f) Add comments above the turn180 ( ) method explaining what the method does, and what theinitial 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 messagesThe compiler is very picky. If you make a mistake in the code or forget something, the compiler willcomplain. It’s useful to be able to recognize some common mistakes and error messages so that youcan 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 tothe 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’(’ expectedmethod cannot be applied to given typesinvalid method declaration’)’ expectedcannot 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 consolePrinting to the console (a separate window) can be useful for testing.

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

Algorithmic thinking and structured programming (in Greenfoot) 21

Page 24: Assignment 1: Meet Dodo - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment1... · Assignment 1: Meet Dodo ... Figure 1: Mimi the Dodo This is Mimi,

Meet Dodo Assignment 1

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 windowmay 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 consolePrinting 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 flowchartshows a print-to-console statement in the repeat-block.

Figure 25: Example flowchart for printing text to the consolec) Use System . out . println ("moved " + nrStepsTaken ); to add the print-to-console statement inthe appropriate place in the code.d) Execute your method by right-clicking on Mimi and calling jump. Note: the console window maybe 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 consoleThe mission is:

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

Algorithmic thinking and structured programming (in Greenfoot) 22

Page 25: Assignment 1: Meet Dodo - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment1... · Assignment 1: Meet Dodo ... Figure 1: Mimi the Dodo This is Mimi,

Meet Dodo Assignment 1

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.

Algorithmic thinking and structured programming (in Greenfoot) 23

Page 26: Assignment 1: Meet Dodo - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment1... · Assignment 1: Meet Dodo ... Figure 1: Mimi the Dodo This is Mimi,

Meet Dodo Assignment 1

ReflectionIn 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. Oneof the most important steps in becoming good at anything is to evaluate and reflect on what you didand how it went. Take one of the challenges in mind that you are proud of to reflect on.ResultI know my solution works because . . .I am proud of my solution because . . .I could improve my solution by . . .MethodMy approach was good because . . .What I could do better next time is . . .

Fill the following table with smileysindicating how things went. I can do itI did it a bit but didn’t fully get itI 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 itscodeGiven 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

Algorithmic thinking and structured programming (in Greenfoot) 24

Page 27: Assignment 1: Meet Dodo - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment1... · Assignment 1: Meet Dodo ... Figure 1: Mimi the Dodo This is Mimi,

Meet Dodo Assignment 1

Diagnostic TestHere 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 () method5. Name a method that belongs to MyDodo but not to Dodo.6. Have a look at the following class diagram:

Figure 27: Class diagram

Algorithmic thinking and structured programming (in Greenfoot) 25

Page 28: Assignment 1: Meet Dodo - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment1... · Assignment 1: Meet Dodo ... Figure 1: Mimi the Dodo This is Mimi,

Meet Dodo Assignment 1

(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 objectgetNrOfEggsHatched () none MyDodo MyDodocanMove () booleanjump ()layEgg () voidturnLeft () Dodo and MyDodocanMove () MyDodogetX ()9. Below are some names for a method which returns the number of eggs found. According to thenaming 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 namingconventions for parameter names, which one is the best?(a) nr_of_eggs

(b) EggCounter

(c) nrOfEggs

(d) eggs

(e) NR_OF_EGGS

Algorithmic thinking and structured programming (in Greenfoot) 26

Page 29: Assignment 1: Meet Dodo - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment1... · Assignment 1: Meet Dodo ... Figure 1: Mimi the Dodo This is Mimi,

Meet Dodo Assignment 1

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 inYou have just finished the assignment. Save your work! You will need this for future assignments. In theGreenfoot menu at the top of the screen, select ’Scenario’ and then ’Save’. You now have all the scenariocomponents in one folder. The folder has the name you chose when you selected ’Save As ...’.Handing inHand 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.

Algorithmic thinking and structured programming (in Greenfoot) 27