+ All Categories
Home > Documents > Assignment 1: Meet Dodo - course.cs.ru.nlcourse.cs.ru.nl/greenfoot/docs/Opdrachten...

Assignment 1: Meet Dodo - course.cs.ru.nlcourse.cs.ru.nl/greenfoot/docs/Opdrachten...

Date post: 11-Mar-2018
Category:
Upload: donhan
View: 218 times
Download: 0 times
Share this document with a friend
29
Assignment 1: Meet Dodo Algorithmic Thinking and Structured Programming (in Greenfoot) c 2017 Renske Smetsers-Weeda & Sjaak Smetsers 1 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 ................................................... 5 1.5 Classes and inheritance .......................................... 5 1.6 The state of an object ............................................ 6 1.7 Parameters and results .......................................... 7 1.8 Signatures .................................................. 7 1.9 Reading owchart and code ........................................ 8 1.10 Java Documentation ........................................... 10 1.11 Modifying, compiling and testing programs .............................. 11 1.12 Naming conventions ........................................... 12 1.13 Errors .................................................... 13 1.14 Printing to the console .......................................... 13 Challenges 15 1.1 Getting started with Greenfoot ...................................... 15 1.2 Creating objects ............................................... 16 1.3 Exploring the accessor method ...................................... 16 1.4 Exploring the mutator method ...................................... 17 1.5 Inheritance ................................................. 18 1.6 States ..................................................... 18 1.7 Calling Accessor Methods ......................................... 19 1.8 Using Parameters .............................................. 19 1 Licensed under the Creative Commons Attribution 4.0 license: https://creativecommons.org/licenses/by/4.0/
Transcript
Page 1: Assignment 1: Meet Dodo - course.cs.ru.nlcourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1/DodoAssignment1...Assignment 1: Meet Dodo AlgorithmicThinkingandStructuredProgramming(inGreenfoot)

Assignment 1: Meet Dodo

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

Contents

Introduction 1

Learning objectives 2

Instructions 2

Theory 31.1 Dodo’s world . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.2 Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.3 Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41.4 Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51.5 Classes and inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51.6 The state of an object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61.7 Parameters and results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71.8 Signatures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71.9 Reading flowchart and code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81.10 Java Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101.11 Modifying, compiling and testing programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111.12 Naming conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121.13 Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131.14 Printing to the console . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13Challenges 151.1 Getting started with Greenfoot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151.2 Creating objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161.3 Exploring the accessor method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161.4 Exploring the mutator method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171.5 Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181.6 States . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181.7 Calling Accessor Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191.8 Using Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191Licensed under the Creative Commons Attribution 4.0 license: https://creativecommons.org/licenses/by/4.0/

Page 2: Assignment 1: Meet Dodo - course.cs.ru.nlcourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1/DodoAssignment1...Assignment 1: Meet Dodo AlgorithmicThinkingandStructuredProgramming(inGreenfoot)

Meet Dodo Assignment 1

1.9 Reading a flowchart and its corresponding code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201.10 Adding a new method turn180() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211.11 Error messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221.12 Printing text to the console . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231.13 Printing variables to the console . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231.14 Printing coordinates to the console . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24Reflection 26

Saving and Handing in 27

Algorithmic thinking and structured programming (in Greenfoot) 2

Page 3: Assignment 1: Meet Dodo - course.cs.ru.nlcourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1/DodoAssignment1...Assignment 1: Meet Dodo AlgorithmicThinkingandStructuredProgramming(inGreenfoot)

Meet Dodo Assignment 1

Introduction

In 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 tobeing 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 codewhere necessary. Re-use of existing code is one of Java’s strengths, because it allows you to make morecomplex programs in less time.Setting

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

You 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(the theory of) Java in full-depth. In such a manner you can gradually learn Java while you’re actu-ally using it to make stuff. You will learn the basic building blocks that are used for algorithms andprograms.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 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 canfind numerous Java tutorials and manuals. Those teach you the rules, but little about how to writea 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 organizedmanner. 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.

Algorithmic thinking and structured programming (in Greenfoot) 1

Page 4: Assignment 1: Meet Dodo - course.cs.ru.nlcourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1/DodoAssignment1...Assignment 1: Meet Dodo AlgorithmicThinkingandStructuredProgramming(inGreenfoot)

Meet Dodo Assignment 1

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 ownwords, describe the difference between amutatormethod and an accessormethod;• 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 furtheron;• scenario ’DodoScenario1’: to be downloaded from the course website2.

Throughout the assignment you will also need to answer some questions. The following must behanded 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 (theassignment) paper.

There are three types of challenges:Recommended. Students who need more practice or with limited programming experi-ence should complete all of these.Mandatory. Everyone must complete these.Excelling. More inquisitive tasks, designed for students who completed 2 star tasks andare ready 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 - course.cs.ru.nlcourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1/DodoAssignment1...Assignment 1: Meet Dodo AlgorithmicThinkingandStructuredProgramming(inGreenfoot)

Meet Dodo Assignment 1

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-upof 12 by 12 squares. Her world is bounded, she can’t get out. Her sole goal in life is to lay and hatcheggs. 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 callingmethods, 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 aheadYou 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).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 - course.cs.ru.nlcourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1/DodoAssignment1...Assignment 1: Meet Dodo AlgorithmicThinkingandStructuredProgramming(inGreenfoot)

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.You can create a new object of MyDodo using new MyDodo ( ). There are two ways to do this:1. directly in the code2. by right-clicking on MyDodo in the class diagram, selecting ”newMyDodo( )” (see figure 4) and thendragging the Dodo into the world.

Figure 4: Creating a new MyDodo object

Theory 1.3: Algorithms

An algorithm is a very precisely defined set of instructions. Program code is an algorithm writtenspecifically for a computer. It tells the computer exactly, step by step, what it should do. If a set ofinstructions has been described precisely enough, someone else should be able to follow the stepsprecisely as you meant it. For the same problem (initial situation) the instructions will lead to exactlythe same outcome (final situation). It is similar to a recipe. The difference with a recipe is that analgorithm is more precise. For example, a recipe might say ”stir until smooth”. However, each time

Algorithmic thinking and structured programming (in Greenfoot) 4

Page 7: Assignment 1: Meet Dodo - course.cs.ru.nlcourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1/DodoAssignment1...Assignment 1: Meet Dodo AlgorithmicThinkingandStructuredProgramming(inGreenfoot)

Meet Dodo Assignment 1

you (or someone else) makes that dessert it may end up differently, one time being a bit smoother thanthe next. In an algorithm, it must be precisely clear what each step exactly means. The result must beexactly the same every time.Theory 1.4: Methods

There are two types of methods, mutator methods and accessor methods Each has its an own specificpurpose.Mutator methods

Amutatormethod is a commandwhichmakes 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

An accessor method is a question which provides information about (the state of) an object. For exam-ple:• 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 whetherMimi 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).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 diagramyou can see that MyDodo belongs to the Dodo family. In Greenfoot, the class diagram is shown onthe right-hand side of the screen. Have a look at figure 5. The arrow in the diagram shows an ’is-a’relationship: MyDodo ’is-a’ Dodo. So, MyDodo belongs to the class Dodo.

Figure 5: Class diagramMyDodo’s methods

Mimi has methods that you can call. Mimi is a MyDodo and can do anything a MyDodo can do. In theworld, right-click on Mimi to see what a MyDodo can do. For example the move( )method.

Algorithmic thinking and structured programming (in Greenfoot) 5

Page 8: Assignment 1: Meet Dodo - course.cs.ru.nlcourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1/DodoAssignment1...Assignment 1: Meet Dodo AlgorithmicThinkingandStructuredProgramming(inGreenfoot)

Meet Dodo Assignment 1

Dodo’s methods

But 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)!In the world, right-click on Mimi. 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 5), Dodoinherits (or gets) all these Dodo methods too. So, because MyDodo is a subclass of Dodo, a MyDodo so canperform all Dodomethods (in addition to its own MyDodomethods).Overerving

The 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 6: Pet class diagramThe class diagram in figure 6 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.

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 severalobjects of the same class in the world at the same time. In the picture below you see three objects ofthe Egg class and one of the MyDodo class.

Figure 7: A world with several objects

Algorithmic thinking and structured programming (in Greenfoot) 6

Page 9: Assignment 1: Meet Dodo - course.cs.ru.nlcourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1/DodoAssignment1...Assignment 1: Meet Dodo AlgorithmicThinkingandStructuredProgramming(inGreenfoot)

Meet Dodo Assignment 1

All 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, in the world right-click on the object and then choose ’Inspect’.The following example shows the state of an Egg-object with coordinates (1,1) and onewith coordinates(2,2).

Figure 8: 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

Results

In 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.Parameters

A 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 jumpneeds this additional information in order to work. Otherwise, it would not know how manycells Mimi must move.• void move( ) has no parameters.• void setDirection( int new_direction ) has one parameter, an int new_directionwhich tellsthe method which direction to turn the object towards.

Types

Parameters and results have a type. The type indicates which sorts of values a parameter or resultmust have. Examples of different types are:Type Meaning Example

int a whole number 2boolean ’true’ or ’false’ trueString 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.

Algorithmic thinking and structured programming (in Greenfoot) 7

Page 10: Assignment 1: Meet Dodo - course.cs.ru.nlcourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1/DodoAssignment1...Assignment 1: Meet Dodo AlgorithmicThinkingandStructuredProgramming(inGreenfoot)

Meet Dodo Assignment 1

Theory 1.8: Signatures

By 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 exam-ple: public void jump (int distance). (the meaning of public will be explained later)

Figure 9: 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.Theory 1.9: Reading flowchart and code

An algorithm can be visually represented in a flowchart. This helps maintain overview, in turnmakingit 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 lookat this method in challenge 1.4.

Algorithmic thinking and structured programming (in Greenfoot) 8

Page 11: Assignment 1: Meet Dodo - course.cs.ru.nlcourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1/DodoAssignment1...Assignment 1: Meet Dodo AlgorithmicThinkingandStructuredProgramming(inGreenfoot)

Meet Dodo Assignment 1

Figure 10: Flowchart and corresponding code for move( )

Figure 11: Flowchart and corresponding code for move( )

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.∗ 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 fol-lowed the ’move’ or the ’turnRight’method will be executed.• When the ’End’ is reached, then themovemethod 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 meansit makes the object do something (as opposed to an accessor method which yields informationabout the object’s state) (See theory 1.4).

Algorithmic thinking and structured programming (in Greenfoot) 9

Page 12: Assignment 1: Meet Dodo - course.cs.ru.nlcourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1/DodoAssignment1...Assignment 1: Meet Dodo AlgorithmicThinkingandStructuredProgramming(inGreenfoot)

Meet Dodo Assignment 1

• 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 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 Documentation

Each 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 Documentation

In Java there are some standard agreements on how to comment code (see the code below for anexample):• 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.• @return indicates what the method returns.

/*** Move given number of cells forward in the current direction.** <p> Initial: Dodo is somewhere in the world.* <p> Final: If possible, Dodo has jumped the distance forwards** @param int distance: the number of steps made* @return nothing*/public void jump( int distance ) {int steps = 0; // steps counter set to 0while ( steps < distance ) { // check if more steps must be takenmove(); // take a stepsteps++; // increment the counter}}

Algorithmic thinking and structured programming (in Greenfoot) 10

Page 13: Assignment 1: Meet Dodo - course.cs.ru.nlcourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1/DodoAssignment1...Assignment 1: Meet Dodo AlgorithmicThinkingandStructuredProgramming(inGreenfoot)

Meet Dodo Assignment 1

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

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

Figure 13: The compile button2. Execute: Call the method by right-clicking on Mimi and then choosing the method.

Algorithmic thinking and structured programming (in Greenfoot) 11

Page 14: Assignment 1: Meet Dodo - course.cs.ru.nlcourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1/DodoAssignment1...Assignment 1: Meet Dodo AlgorithmicThinkingandStructuredProgramming(inGreenfoot)

Meet Dodo Assignment 1

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 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 testingin between, then debugging (detecting errors in your code) can become a time-consuming and veryfrustrating task!Theory 1.12: Naming 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.Amethod’s name:

• is meaningful: it is consistent with what the method does• 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 startswith 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

Algorithmic thinking and structured programming (in Greenfoot) 12

Page 15: Assignment 1: Meet Dodo - course.cs.ru.nlcourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1/DodoAssignment1...Assignment 1: Meet Dodo AlgorithmicThinkingandStructuredProgramming(inGreenfoot)

Meet Dodo Assignment 1

• 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 startswith a capital letter• for example: nrOfEggsSee http://google-styleguide.googlecode.com/svn/trunk/javaguide.html for a completeoverview 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. Whenthe compiler finds an error, it will highlight the rownumber red. When you click on it, the compilerwill elaborate (see figure 15)It’s up to you to find and fix the mistake.

Figure 15: Compiler errorsSome common mistakes are:Mistake Compiler error messagemissing ’;’ at the end of the line ’;’ expectedmissing ’( )’ in the header ’(’ expected or ’illegal start of expression’missing ’{’ 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 ’(’ expected or ’not a statement’typo (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 errors

Besides syntax errors, there are also other types of programming errors. The compiler will not com-plain, but the program does not do what is expected. This is called a logical error. Such an error canbe 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 as-signment. By using a structured approach to programming you can significantly reduce the chance ofthese types of errors slipping into your code.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 example code for printing text in the console:

Algorithmic thinking and structured programming (in Greenfoot) 13

Page 16: Assignment 1: Meet Dodo - course.cs.ru.nlcourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1/DodoAssignment1...Assignment 1: Meet Dodo AlgorithmicThinkingandStructuredProgramming(inGreenfoot)

Meet Dodo Assignment 1

public void printingToConsole( ){String message = "Hello";int nrOfEggs = 5;System.out.println ( message );System.out.println ( message + " Mimi!" );System.out.println ( nrOfEggs );System.out.println ( "There are " + nrOfEggs + " eggs." );}

And this is its corresponding output in the console:

Figure 16: The consoleDepending on what needs to be printed, the printlnmethod 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) 14

Page 17: Assignment 1: Meet Dodo - course.cs.ru.nlcourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1/DodoAssignment1...Assignment 1: Meet Dodo AlgorithmicThinkingandStructuredProgramming(inGreenfoot)

Meet Dodo Assignment 1

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 downloadand install Greenfoot 3.0.4 (if it has not already been done for you, you can download it at ) and openthe 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 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: ’Do-doScenario1.zip’.

• Copy the zip-file to the folder which you have chosen.• Unpack the zip-file at that location by right-clicking on the file and choosing Extract All....

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) 15

Page 18: Assignment 1: Meet Dodo - course.cs.ru.nlcourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1/DodoAssignment1...Assignment 1: Meet Dodo AlgorithmicThinkingandStructuredProgramming(inGreenfoot)

Meet Dodo Assignment 1

Figure 17: 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 objects

We’re going to make the scenario as shown in figure 3:a) Right-click onMyDodo, 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 method

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

Algorithmic thinking and structured programming (in Greenfoot) 16

Page 19: Assignment 1: Meet Dodo - course.cs.ru.nlcourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1/DodoAssignment1...Assignment 1: Meet Dodo AlgorithmicThinkingandStructuredProgramming(inGreenfoot)

Meet Dodo Assignment 1

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.

Figure 18: Dialogue box for canMove( )b) Can you move Mimi to another location so that boolean canMove( ) returns a different resultthan true?c) What do you think booleanmeans?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 thereany 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 intmean?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 about an object, but doesn’t changethe situation or state of an object.Challenge 1.4: Exploring the mutator method

OurMyDodo has been programmed to do several things. You can let her do things (give her commands)by calling hermutator methods.a) In the world, right-click on Mimi. You will see a list of all the things Mimi can do (in other words,which methods you can call), for example move( ), and hatchEgg( ). Name one other methodwhich makes Mimi do something.b) We will now explore what the method void move( ) does.

i. Drag Mimi to the centre of the world. Call Mimi’s method void move( ). Can you describewhat the method does?ii. DragMimi to the edge of theworld, facing outwards. Call Mimi’smethod void move( ) again.What happens now?iii. Using what you have just seen, match A, B and C in the flowchart in figure 19 to its corre-sponding code below.

Algorithmic thinking and structured programming (in Greenfoot) 17

Page 20: Assignment 1: Meet Dodo - course.cs.ru.nlcourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1/DodoAssignment1...Assignment 1: Meet Dodo AlgorithmicThinkingandStructuredProgramming(inGreenfoot)

Meet Dodo Assignment 1

Figure 19: Flowchart for MyDodo’s move( )method/*** Move one cell forward in the current direction.** <P> Initial: Dodo is somewhere in the world* <P> Final: If possible, Dodo has moved forward one cell**/public void move() {if ( canMove() ) {step();} else {showError( "I’m stuck!" );}}

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) Have a look at the class diagram on the right of the screen. Mimi is a MyDodo. All MyDodos areDodos. 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. In the world, right-click on Mimi. Choose’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 MyDodo’s have, but Dodos don’t.We have now seen that Mimi, and all other MyDodos, inherit and thus can execute all Dodomethods.

Please read Theory 1.6: The state of an object.

Algorithmic thinking and structured programming (in Greenfoot) 18

Page 21: Assignment 1: Meet Dodo - course.cs.ru.nlcourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1/DodoAssignment1...Assignment 1: Meet Dodo AlgorithmicThinkingandStructuredProgramming(inGreenfoot)

Meet Dodo Assignment 1

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 andint y) coordinates?b) Investigate what the coordinates are at each of the corners. Draw in the coordinates in figure 20.The top-left corner has already been done for you.

Figure 20: 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. Accessormethods are used to return this information. That way the information can be used. Let’s have a lookat how returning a result 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 onMimi. Call the method jump(intdistance). This method requires an int (whole number) as a parameter so that it knows howfar (’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 theparameter. 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)

Algorithmic thinking and structured programming (in Greenfoot) 19

Page 22: Assignment 1: Meet Dodo - course.cs.ru.nlcourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1/DodoAssignment1...Assignment 1: Meet Dodo AlgorithmicThinkingandStructuredProgramming(inGreenfoot)

Meet Dodo Assignment 1

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

Figure 21: Error message when using text as a parameter

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 therealready.a) Have a look at the code for the boolean canLayEgg( )method below. The flowchart in figure 22visualizes the algorithm. Fill in the missing gaps for A,B,C,D (in the flowchart) and E (in the code).

/*** Test if Dodo can lay an egg.* (there is not already an egg in the cell)** <p> Initial: Dodo is somewhere in the world* <p> Final: Same as initial situation** @return boolean true if Dodo can lay an egg (no egg there)* false if Dodo can’t lay an egg* (already an egg in the cell)*/public boolean canLayEgg( ){if( onEgg( ) ) {// E} else {return true;}}

Algorithmic thinking and structured programming (in Greenfoot) 20

Page 23: Assignment 1: Meet Dodo - course.cs.ru.nlcourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1/DodoAssignment1...Assignment 1: Meet Dodo AlgorithmicThinkingandStructuredProgramming(inGreenfoot)

Meet Dodo Assignment 1

Figure 22: Flowchart for canLayEgg( )methodb) Open MyDodo’s code in the editor: Right-click MyDodo in the class diagram and select ’Open editor’.c) Find the canLayEgg( )method. Tip: use Ctrl+F.d) Remove the comments in front of the code.e) Replace ’E’ with the correct code.f) Test your method. Right-click on Mimi in the world and select the canLayEgg( ) method. Testseveral situations.

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 for turn180

Algorithmic thinking and structured programming (in Greenfoot) 21

Page 24: Assignment 1: Meet Dodo - course.cs.ru.nlcourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1/DodoAssignment1...Assignment 1: Meet Dodo AlgorithmicThinkingandStructuredProgramming(inGreenfoot)

Meet Dodo Assignment 1

a) Have a look at the flowchart and the code below. Fill in the missing gaps for A and B.public void A ( ) {turnRight( );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).

Figure 24: Compile buttonIf necessary fix any mistakes.

e) Call your newmethod by right-clicking onMimi 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.g) Test your program after each modification, also this one.

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 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( )

Algorithmic thinking and structured programming (in Greenfoot) 22

Page 25: Assignment 1: Meet Dodo - course.cs.ru.nlcourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1/DodoAssignment1...Assignment 1: Meet Dodo AlgorithmicThinkingandStructuredProgramming(inGreenfoot)

Meet Dodo Assignment 1

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 console

Printing to the console (a separate window) can be useful for testing.a) Find the code for your turn180( )method.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 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 flowchartshows a print-to-console statement in the repeat-block.

Algorithmic thinking and structured programming (in Greenfoot) 23

Page 26: Assignment 1: Meet Dodo - course.cs.ru.nlcourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1/DodoAssignment1...Assignment 1: Meet Dodo AlgorithmicThinkingandStructuredProgramming(inGreenfoot)

Meet Dodo Assignment 1

Figure 25: Example flowchart for printing text to the consolec) Use System.out.println("moved "+ nrStepsTaken); to add the print-to-console statement in theappropriate 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 console

The mission is: ”Mimi walks across her row printing her coordinates to the console at each step.”

Algorithmic thinking and structured programming (in Greenfoot) 24

Page 27: Assignment 1: Meet Dodo - course.cs.ru.nlcourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1/DodoAssignment1...Assignment 1: Meet Dodo AlgorithmicThinkingandStructuredProgramming(inGreenfoot)

Meet Dodo Assignment 1

/*** Walks to edge of the world printing the coordinates at each step** <p> Initial: Dodo is on West side of world facing East.* <p> Final: Dodo is on East side of world facing East.* Coordinates of each cell printed in the console.*/

public void walkToWorldEdgePrintingCoordinates( ){while( ! borderAhead( ) ){//print coordinatesmove();}}

a) In MyDodo find the methode walkToWorldEdgePrintingCoordinates( ).b) Add the code for printing the coordinates.c) Test your method. Does it also print the last coordinate?d) 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) 25

Page 28: Assignment 1: Meet Dodo - course.cs.ru.nlcourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1/DodoAssignment1...Assignment 1: Meet Dodo AlgorithmicThinkingandStructuredProgramming(inGreenfoot)

Meet Dodo Assignment 1

Reflection

In this assignment you have become acquainted with Greenfoot. You have also been introduced tocode. You adjusted code yourself, and practiced compiling and testing each small change that youmade. One of the most important steps in becoming good at anything is to evaluate and reflect onwhat 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 smileysindicating 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 andits codeI can find a method’s code in the Greenfoot editor

I can incrementally make changes to code

I can add a method, compile, run and test

Algorithmic thinking and structured programming (in Greenfoot) 26

Page 29: Assignment 1: Meet Dodo - course.cs.ru.nlcourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1/DodoAssignment1...Assignment 1: Meet Dodo AlgorithmicThinkingandStructuredProgramming(inGreenfoot)

Meet Dodo Assignment 1

Saving and Handing in

You have just finished the assignment. Save your work! You will need this for future assignments. Inthe Greenfoot menu at the top of the screen, select ’Scenario’ and then ’Save’. You now have all thescenario 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.

Algorithmic thinking and structured programming (in Greenfoot) 27


Recommended