Assignment 1: Meet Dodo

Similar documents
Assignment 1: Meet Dodo

Assignment 4: Dodo gets smarter

Assignment 6: Dodo keeps getting smarter

Assignment 3: Optimizing solutions

Assignment 8: Sokoban

Algorithmic Thinking and Structured Programming (in Greenfoot) Teachers: Renske Smetsers-Weeda Sjaak Smetsers

Assignment 7: Dodo s Race

Algorithmic Thinking and Structured Programming (in Greenfoot) Teachers: Renske Smetsers Sjaak Smetsers

Algorithmic Thinking and Structured Programming (in Greenfoot) Teachers: Renske Smetsers-Weeda Sjaak Smetsers Ana Tanase

The first program: Little Crab

Getting to know Greenfoot

Algorithmic Thinking and Structured Programming (in Greenfoot) Teachers: Renske Smetsers-Weeda Sjaak Smetsers Ana Tanase

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

Algorithmic Thinking and Structured Programming (in Greenfoot) Teachers: Renske Smetsers-Weeda Sjaak Smetsers

1 Getting started with Processing

Laboratory 1: Eclipse and Karel the Robot

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

The compiler is spewing error messages.

Excel Basics: Working with Spreadsheets

Algorithmic Thinking and Structured Programming (in Greenfoot) Teachers: Renske Smetsers-Weeda Sjaak Smetsers Ana Tanase

Programming Using C# QUEEN S UNIVERSITY BELFAST. Practical Week 7

Chapter 4 Defining Classes I

ALICE: An introduction to progamming

Initial Coding Guidelines

A A B U n i v e r s i t y

Chapter 1: First Steps to Greenfoot 1

Programming for Beginners

Improving the Crab more sophisticated programming

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Hello World! Computer Programming for Kids and Other Beginners. Chapter 1. by Warren Sande and Carter Sande. Copyright 2009 Manning Publications

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller

Procedures: Algorithms and Abstraction

ASCII Art. Introduction: Python

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class

We will work with Turtles in a World in Java. Seymour Papert at MIT in the 60s. We have to define what we mean by a Turtle to the computer

Java Programming Constructs Java Programming 2 Lesson 1

Simulations How To for Fathom

COMP 250 Winter 2011 Reading: Java background January 5, 2011

Get JAVA. I will just tell you what I did (on January 10, 2017). I went to:

Improving the crab: more sophisticated programming

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

Access Intermediate

Variables, expressions and statements

Creating Java Programs with Greenfoot

Have the students look at the editor on their computers. Refer to overhead projector as necessary.

Creating Java Programs with Greenfoot

Your First Windows Form

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0. L J Howell UX Software Ver. 1.0

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

1 Getting started with Processing

Compilation and Execution Simplifying Fractions. Loops If Statements. Variables Operations Using Functions Errors

Jerry Cain Handout #5 CS 106AJ September 30, Using JSKarel

Using Karel with Eclipse

Welcome to Computers for ESL Students, 4th Edition

FILE ORGANIZATION. GETTING STARTED PAGE 02 Prerequisites What You Will Learn

On the Web sun.com/aboutsun/comm_invest STAROFFICE 8 DRAW

Lesson 3: Basic Programming Concepts

PYTHON YEAR 10 RESOURCE. Practical 01: Printing to the Shell KS3. Integrated Development Environment

Lua - Instruction Manual

Introduction to Microsoft Word 2010

Java for Non Majors. Final Study Guide. April 26, You will have an opportunity to earn 20 extra credit points.

Major Assignment: Pacman Game

Physics 306 Computing Lab 1: Hello, World!

File Management Tutorial

Creating objects TOPIC 3 INTRODUCTION TO PROGRAMMING. Making things to program with.

Problem Solving through Programming with Greenfoot. Mark Lewis

Using Flash Animation Basics

Civil Engineering Computation

Getting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners

Contents. How to use Magic Ink... p Creating Magic Revealers (with Magic Ink)... p Basic Containers... p. 7-11

(Refer Slide Time: 1:27)

CS 231 Data Structures and Algorithms, Fall 2016

Mr. Monroe s Guide to Mastering Java Syntax

Access Intermediate

Valuable points from Lesson 6 Adobe Flash CS5 Professional Classroom in a Book

Using Microsoft Excel

Documentation Requirements Computer Science 2334 Spring 2016

In this lesson you will learn: How to capture the input from the user. How to write programs using variables and lists. Athletics Swimming Gymnastics

FACULTY AND STAFF COMPUTER FOOTHILL-DE ANZA. Office Graphics

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Making use of other Applications

Creating Vector Shapes Week 2 Assignment 1. Illustrator Defaults

[ the academy_of_code] Senior Beginners

5.6.1 The Special Variable this

Outline. Turtles. Creating objects. Turtles. Turtles in Java 1/27/2011 TOPIC 3 INTRODUCTION TO PROGRAMMING. Making things to program with.

How to make a Work Profile for Windows 10

Game keystrokes or Calculates how fast and moves a cartoon Joystick movements how far to move a cartoon figure on screen figure on screen

How To Upload Your Newsletter

Interactive Tourist Map

Outlook Web Access. In the next step, enter your address and password to gain access to your Outlook Web Access account.

Barchard Introduction to SPSS Marks

Preprocessor Directives

Intro. Scheme Basics. scm> 5 5. scm>

EXCEL BASICS: MICROSOFT OFFICE 2007

CPS122 Lecture: Defining a Class

Chapter 15: Object Oriented Programming

Grade Point Scales Standard Honors AP/College A B C D F Sample file

CMPT 100 : INTRODUCTION TO

Transcription:

Assignment 1: Meet Dodo Algorithmic Thinking and Structured Programming (in Greenfoot) 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....................................................... 4 1.5 Classes and inheritance............................................. 4 1.6 The state of an object............................................... 5 1.7 Parameters and results.............................................. 6 1.8 Signatures...................................................... 7 1.9 Reading flowchart and code........................................... 7 1.10 Java Documentation............................................... 9 1.11 Modifying, compiling and testing programs................................. 10 1.12 Naming conventions............................................... 11 1.13 Errors........................................................ 12 1.14 Printing to the console............................................. 12 Challenges 14 1.1 Getting started with Greenfoot......................................... 14 1.2 Creating objects.................................................. 15 1.3 Exploring the accessor method......................................... 15 1.4 Exploring the mutator method......................................... 16 1.5 Inheritance..................................................... 17 1.6 States......................................................... 17 1.7 Calling Accessor Methods............................................ 18 1.8 Using Parameters................................................. 18 1 Licensed under the Creative Commons Attribution 4.0 license: https://creativecommons.org/licenses/by/4.0/

1.9 Reading a flowchart and its corresponding code.............................. 19 1.10 Adding a new method turn180()....................................... 20 1.11 Error messages.................................................. 21 1.12 Printing text to the console........................................... 21 1.13 Printing variables to the console....................................... 22 1.14 Printing coordinates to the console...................................... 22 Reflection 24 Diagnostic Test 25 Saving and Handing in 27 Algorithmic thinking and structured programming (in Greenfoot) 2

Introduction In this series of assignments, Algorithmic Thinking and Structured Programming (in Greenfoot), you will learn Algorithmic Thinking and the basics of Object Oriented programming... and (hopefully will) be having fun in the process. After completion you will be able to program in Java, in addition to being able to use Greenfoot and Java libraries. With these skills, you will be able to quickly learn other (Object Oriented) programming languages. You will also learn how to use and adapt existing code where necessary. Re-use of existing code is one of Java s strengths, because it allows you to make more complex programs in less time. Programming You will program in the Java language. For the assignments we will use the Greenfoot programming environment. This is an environment that allows you to write Java code without first having to learn (the theory of) Java in full-depth. In such a manner you can gradually learn Java while you re actually using it to make stuff. You will learn the basic building blocks that are used for algorithms and programs. Setting Figure 1: Mimi the Dodo This is Mimi, our Dodo. A Dodo (a bird which is now extinct) was never very intelligent. At first you will teach the Dodo simple tasks, like walking and turning. Throughout the course, you will teach the Dodo to complete more complex tasks, such as independently walking through any given maze. One of the final tasks is a competition with your classmates: who can make the smartest Dodo? Computational Thinking Computational thinking involves solving problems, designing systems, and understanding human behavior. It s not about trying to get humans to think like computers; it is a way humans solve problems. Thinking like a computer scientist means more than being able to program a computer. It requires problem solving. If you want to learn how to play chess, you have to know the rules. These rules tell you what you can and what you can t do. But if you want to play chess well and enjoy playing the game, then merely knowing the rules is not enough. You also have to learn what a good move is. On internet you can find numerous Java tutorials and manuals. Those teach you the rules, but little about how to write a program well. In this course you will learn how to systematically deal with a programming task. You will learn to analyze problems and develop an appropriate solution in a structured and organized manner. The goal is to teach you to program well, and let you enjoy doing so. Goals The course is divided into several assignments. This assignment s goals are: To learn how to make code modifications in a structured manner; Become acquainted with the Greenfoot environment. Algorithmic thinking and structured programming (in Greenfoot) 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 own words, describe the difference between a mutator method and an accessor method; identify and list (inherited) methods of a class; use a class diagram to identify classes and subclasses; identify properties of an object s state; describe what the types int, String, void, and boolean are; given a signature, identify a method s result type and parameter(type)s; describe the relationship between an algorithm, a flowchart and program code; add JavaDoc comments to code; incrementally make code modifications and then compile and test; recognize and interpret (syntax) errors; print to a console. Instructions For this assignment you will need: Greenfoot: Instructions for installing and opening the Greenfoot environment are given further on; scenario DodoScenario1 : to be downloaded from the course website 2. Throughout the assignment you will also need to answer some questions. The following must be handed in: All flowcharts: use pencil and paper, or go to https://www.draw.io/; Your code: the file MyDodo. jav contains all your code and must be handed in; The reflection sheet: complete and hand it in. You must discuss all other answers with a programming partner. Jot down a short answer on (the assignment) paper. There are three types of challenges: Recommended. Students who need more practice or with limited programming experience should complete all of these. Mandatory. Everyone must complete these. Excelling. More inquisitive tasks, designed for students who completed 2 star tasks and are ready for a bigger challenge. Students who skip 1-star challenges should complete all 3-star challenges. 2 http://course.cs.ru.nl/greenfoot/ Algorithmic thinking and structured programming (in Greenfoot) 2

Theory Theory 1.1: Dodo s world Mimi belongs to the Dodo family. Here she is, facing East. Mimi lives in a (grid)world that is made-up of 12 by 12 squares. Her world is bounded, she can t get out. Her sole goal in life is to lay and hatch eggs. The picture shows the world s coordinate system. Figure 2: Mimi s world Mimi is a very well-behaved Dodo. She does exactly what she is told to do, and she always gives honest answers to your questions (she never lies). By calling methods, you can tell her to do something or ask her questions. You can let Mimi do things, such as: move hatchegg jump move one square ahead hatch an egg jump several squares ahead You can also ask Mimi a question, such as: canmove getnrofeggshatched Can you take a step forward? How many eggs have you hatched? Theory 1.2: Objects A world consists of objects (also known as class instances, or simply instances). By selecting new MyDodo ( ) you can create a new object of MyDodo. The world below shows one MyDodo object and three Egg objects. Algorithmic thinking and structured programming (in Greenfoot) 3

Figure 3: Scenario with one MyDodo object and three Egg objects In our assignments we have one lead actress, a MyDodo object. She is an instance of MyDodo. We will call her Mimi. Theory 1.3: Algorithms An algorithm is a very precisely defined set of instructions. Program code is an algorithm written specifically for a computer. It tells the computer exactly, step by step, what it should do. If a set of instructions has been described precisely enough, someone else should be able to follow the steps precisely as you meant it. For the same problem (initial situation) the instructions will lead to exactly the same outcome (final situation). It is similar to a recipe. The difference with a recipe is that an algorithm is more precise. For example, a recipe might say stir until smooth. However, each time you (or someone else) makes that dessert it may end up differently, one time being a bit smoother than the next. In an algorithm, it must be precisely clear what each step exactly means. The result must be exactly the same every time. Theory 1.4: Methods There are two types of methods, mutator methods and accessor methods, each with an own purpose: Mutator methods These are commands which make an object do something. It changes the state of an object. You can recognize a mutator method by its result: void. For example: void move ( ) changes the state of Dodo by moving it one cell ahead. void setdirection ( int new_direction ) changes the direction in which an object is facing. Accessor methods These are questions that provide information about (the state of) an object. For example: int getnrofeggshatched ( ) which returns an int (an integer, or whole number) indicating how many eggs Mimi has hatched. boolean canmove ( ) which returns a boolean (either true or false), indicating whether Mimi can take a step forwards or not. Accessor methods only provide information about an object, they don t do anything with an object: the object s state remains unchanged (for example, Dodo doesn t also move to another position). Algorithmic thinking and structured programming (in Greenfoot) 4

Theory 1.5: Classes and inheritance Every object belongs to a class. As such, Mimi is an instance of the MyDodo class. In the class diagram you can see that MyDodo belongs to the Dodo family. In Greenfoot, the class diagram is shown on the right-hand side of the screen. Have a look at figure 4. The arrow in the diagram shows an is-a relationship: MyDodo is-a Dodo. So, MyDodo belongs to the class Dodo. Figure 4: Class diagram MyDodo s methods Mimi is a MyDodo. Mimi has methods that you can call. By right-clicking on Mimi you can see what a MyDodo (and thus Mimi) can do. For example the move ( ) method. Dodo s methods But Mimi (our MyDodo) is capable of doing much more. There are things that all Dodos, in general, can do. Mimi is a Dodo, so of course she can also do all the the things that Dodo s can do too (and much more)! Right-click on Mimi (in the world). At the top of the list you see inherited from Dodo. If you click on that, then more methods will appear, such as layegg ( ). These are methods which belong to the class Dodo, things that all Dodos can do. Because MyDodo is a Dodo (see the class diagram in figure 4), Dodo inherits (or gets) all these Dodo methods too. So, because MyDodo is a subclass of Dodo, a MyDodo so can perform all Dodo methods (in addition to its own MyDodo methods). Inheritance The fact that MyDodo can borrow methods from her superclass Dodo is called inheritance. By using inheritance, a new class can be introduced as an extension of an existing class. An instance of a subclass can use all the methods from its superclass. In such a situation, the existing class is called the super class, and the extended class is called the subclass. Because MyDodo a subclass of Dodo, a MyDodo can execute methods from both the Dodo class as well as its own MyDodo class. Example of a class diagram Figure 5: Pet class diagram The class diagram in 5 shows that Cats and Dogs are subclasses of PetAnimal. Every PetAnimal can sleep () and eat (), thus so can Cats and Dogs. A Cat can meow (). This method is specific to only Cats. Algorithmic thinking and structured programming (in Greenfoot) 5

Theory 1.6: The state of an object You can place different objects in the world, such as a Dodo and an egg. You can also place several objects of the same class in the world at the same time. In the picture below you see three objects of the Egg class and one of the MyDodo class. Figure 6: A world with several objects All objects of the same class have the same methods, and thus have the same behavior. The three objects of Egg look identical and can do exactly the same things. Yet, they are different objects, or instances. Every object has its own state. States are made up of characteristics such as coordinates or appearance. To view the state of an object, right-click on the object and then choose Inspect. The following example shows the state of an Egg-object with coordinates (1,1) and one with coordinates (2,2). Figure 7: States of two Egg-objects Just like you re different from the person sitting next to you, even though you are both people. The mere fact that you are each sitting on different chairs or had something different for breakfast, makes you different. The same is true in the Greenfoot world. Every object has its own state. Theory 1.7: Parameters and results Results In section 1.4 we saw that accessor methods give information about an object s state (they answers questions). Such an answer is called the result of a method. For example, int getnrofeggshatched ( ) has an int (whole number) as its result. Parameters A method can also be given a certain value. This value, called a parameter, gives the method more information about a particular task. A method can have 0 or more parameters. Examples: void jump ( int distance ) has one parameter, distance, which tells the method how far it must jump. We can also tell that distance is a whole number, an int. By calling jump (3); Mimi will move forward 3 cells. By calling jump (5); Mimi will move forward 5 cells. The method jump needs this additional information in order to work. Otherwise, it would not know how many cells Mimi must move. void move ( ) has no parameters. void setdirection ( int new_direction ) has one parameter, an int new_direction which tells the method which direction to turn the object towards. Algorithmic thinking and structured programming (in Greenfoot) 6

Types Parameters and results have a type. The type indicates which sorts of values a parameter or result must have. Examples of different types are: Type Meaning Example int a whole number 2 boolean true or false true String text enclosed in quote marks I lost my pen. List list [1,2,3] A class can also be a type, such as a List of Eggs. It is not possible to call void jump ( int distance ) with no parameters because this method requires an int as a parameter. Theory 1.8: Signatures By looking at the signature of a method, you can see which parameters, parameter types and result types belong to the method. Method name: the method s name is indicated in front of the first parenthesis. In this example: jump. Parameter: the parameters that the method requires are indicated in between the parentheses ( and ). In this example: distance. Parameter type: the parameter s type (such as int, boolean, or String) is indicated in front of the parameter s name. In this example: int. Result type: the result s type (such as int, boolean, void) is indicated in front of the method s name. In this example the result type is void. This method doesn t return anything (it is a mutator method). Method s signature: together, all of the components above are called the signature. In this example: public void jump ( int distance ). (the meaning of public will be explained later) For the example above: Figure 8: Signature of a method Method name jump Parameter distance Parameter type int Result type void Method s signature public void jump ( int distance ) The types in the signature indicate which types of values a parameter or result must have. Algorithmic thinking and structured programming (in Greenfoot) 7

Theory 1.9: Reading flowchart and code An algorithm can be visually represented in a flowchart. This helps maintain overview, in turn making it easier to write, read and analyse code. As an example we will look at the algorithm of MyDodo s move ( ) method. We have already had a look at this method in challenge 1.1.4. Figure 9: Flowchart and corresponding code Figure 10: Flowchart and corresponding code The flowchart explained Method name: move. The name can be found in the top-left corner. Initial and final situations are described in the note blocks in the top-right and bottom-right corners. 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

* If canmove? is True, then the arrow to the right is followed. This behavior is consistent with that of an if.. then.. else statement in the code. In the case of a rectangle, a method is called. So, depending on which arrow has been followed the move or the turnright method will be executed. When the End is reached, then the move method is finished. The code explained Comment: the text in between /** and */ (shown in blue text in the Greenfoot editor) are comments. The compiler doesn t do anything with this. Programmers write comments in their code to help others understand their programs. The initial and final situations are described here. For comments in the code that fit on just one line, use //. Signature: this is public void move ( ). Access modifier: public. What this means and which other possibilities there are, will be explained later. Method name: move. Result type: void. What the method returns. This mutator method returns void which means it makes the object do something (as opposed to an accessor method which yields information about the object s state) (See theory 1.4). Body: this is the part between the first curly bracket { and its corresponding curly bracket } : what the method actually does. In this example you see a conditional expression: the if.. then.. else in the move ( ). It works like this: The condition is stated in between the parentheses ( and ). Firstly, the condition canmove is checked. * If the condition is true, then the code directly following the condition is executed. Thus, step ( ) is executed and Dodo takes a step. * If the condition is false, then the code after the else is executed. Thus, an error message with the text I m stuck is shown. Theory 1.10: Java Documentation Each method should have comments clarifying what the code does. In Java this is called JavaDoc ( Java Documentation ). Documenting your codes helps others (and yourself) understand and re-use code. Writing Java Documentation In Java there are some standard agreements on how to comment code (see figure 11 for an example): Each method has comments (globally) describing what the method does. Each method explains the initial and final situation. Comments are started by /** and ended by */. For comments not longer than one line can, you can use // followed by the comment. @param indicates which parameters the method receives. Algorithmic thinking and structured programming (in Greenfoot) 9

@return indicates what the method returns. Figure 11: Comments belonging to the jump method Viewing Java Documentation To view your code s Java Documentation follow the following steps: 1. Open the code in the editor. 2. At the top-right of the screen, select Documentation instead of Source Code. (See figure 12) Figure 12: Selecting Java documentation instead of Source Code Theory 1.11: Modifying, compiling and testing programs To get Mimi to do more exciting things, you must write your own new methods. Obviously, you must first learn to read code before you can write code. Also, you should be able to describe which changes you want to make, after which you can actually make modifications to existing code. Modifications Always make changes incrementally. A typo can be introduced easily, whilst detecting it could be more troublesome. It is a good idea to compile, run and test every (small) change to the code so that you can quickly locate any mistakes. After each code change: 1. Compile: Press the Compile button on the top-left of the screen. Algorithmic thinking and structured programming (in Greenfoot) 10

Figure 13: The compile button 2. Execute: Call the method by right-clicking on Mimi and then choosing the method. Figure 14: Executing a method by right-clicking on Mimi in the world 3. Test: Check if the method does what you expect. Compare the initial and final situations. Work in a structured manner Make a habit of always following these steps after every code change. That way, if you make a mistake, you can quickly find what the problem is. If you make many changes in one go without testing in between, then debugging (detecting errors in your code) can become a time-consuming and very frustrating task! Theory 1.12: Naming conventions Naming conventions Methods and parameters have names. In Java, there are general conventions (or agreements) on how to choose a name. By following these conventions, your code becomes easier to read and understand for others. A method s name: is meaningful: it is consistent with what the method does Algorithmic thinking and structured programming (in Greenfoot) 11

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 characters (with the exception of ) is written in lowercasecamel: starts with a lowercase letter, and each subsequent word starts with a capital letter for example: canmove A parameter s name: is meaningful: it is consistent with what the parameter means consists of one or more nouns consists of letters and numbers: it does not consist of spaces, commas, or other strange characters (with the exception of ) is written in lowercasecamel: starts with a lowercase letter, and each subsequent word starts with a capital letter for example: nrofeggs See http://google-styleguide.googlecode.com/svn/trunk/javaguide.html for a complete overview of style and naming conventions. Theory 1.13: Errors Syntax errors If you type in something which the compiler does not understand, this is called a syntax error. Some common mistakes are: Mistake missing ; at the end of the line missing ( ) in the header missing { at beginning of body missing } at end of body missing } at end of class missing ( ) in method call typo (watch out for capital/lowercase) wrong parameter type used no parameter used wrong return type wrong type used Compiler error message ; expected ( expected ; expected illegal start of expression reached end of file when parsing not a statement cannot find symbol incompatible types method cannot be applied to given types incompatible types: unexpected return value cannot find symbol Logical errors Besides syntax errors, there are also other types of programming errors. The compiler will not complain, but the program does not do what is expected. This is called a logical error. Such an error can be very difficult to find, and can be very frustrating. Searching for such an error is called debugging. Because prevention is beter than curing, we will discuss good programming practices in the next assignment. By using a structured approach to programming you can significantly reduce the chance of these types of errors slipping into your code. Algorithmic thinking and structured programming (in Greenfoot) 12

Theory 1.14: Printing to the console When debugging, it can be useful to print values or statements to determine where errors are located. To make a console window appear with text you can use the following Java method: System. out. println ( String );. The following example shows the output in the console and its corresponding code. Figure 15: Printing in the console Depending on what needs to be printed, the println method is called with different arguments: Place text in between quotation marks and. To show the value of a variable (such as an integer, double or string), the quotation marks are not needed, just use the variable name. Combine texts and variables using +. Note: For more information about the Java println method, have a look at: https://docs.oracle.com/javase/ 7/docs/api/java/io/PrintStream.html#println(java.lang.String). Algorithmic thinking and structured programming (in Greenfoot) 13

Challenges Challenge 1.1: Getting started with Greenfoot Starting Greenfoot We re going to play around with Mimi in the Greenfoot environment. To do this, you must download and install Greenfoot 3.0.4 (if it has not already been done for you, you can download it at ) and open the given scenario. Download and install Greenfoot Version 3.0.4 (if not already done): Choose a folder: Download: Go to http://www.greenfoot.org/download. Download the appropriate version for your operating system and follow the instructions for installation. Decide where you will save all your work. If you wish, you can use a USB-stick for this. Go to the course page and download the scenario files belonging to this assignment: Copy the given exe-file with initial scenario to the folder which you have chosen. Unpack the scenario at that location, just by clicking on the exe-file. Open the Greenfoot environment: Double click on the Greenfoot.exe file. The programming environment should start now. Open the scenario: Select Scenario in the main menu, and then Open. Navigate to the DodoScenario1 scenario (which you downloaden en unzipped) and chose Open. Rename the scenario: In the Greenfoot menu at the top of the screen, select Scenario and then Save As.... Check that the window opens in the folder where you want to save your work. Choose a file name containing your own name(s) and assignment number, for example: Asgmt1_John. You should see the following: Algorithmic thinking and structured programming (in Greenfoot) 14

Figure 16: What you see when you open the DodoScenario1 scenario Please read Theory 1.1: Dodo s world. Please read Theory 1.2: Objects. Challenge 1.2: Creating objects We re going to make the scenario as shown in figure 3: a) Right-click on MyDodo, on the far right-hand of the screen. b) Select new MyDodo ( ) to create a new MyDodo object. c) Drag the object, our MyDodo called Mimi, to a random position in the world. d) In the same manner, place three BlueEggs in the world. Tip: hold down the Shift button on your keyboard to place multiple blue eggs. Please read Theory 1.3: Algorithms. Please read Theory 1.4: Methods. Challenge 1.3: Exploring the accessor method By right-clicking on Mimi, you can see a list of all the things she can do (in other words, which methods you can call). By using some of those methods (called accessor methods) you can get Mimi to answer questions about herself. a) Drag Mimi into the middle of the world. Right-click on Mimi, and call the boolean canmove ( ) method. A dialogue box appears, as shown below. The method returns true. Algorithmic thinking and structured programming (in Greenfoot) 15

Figure 17: Dialogue box for canmove ( ) b) Can you move Mimi to another location so that boolean canmove ( ) returns a different result than true? c) What do you think boolean means? d) Besides returning a result, let s have a look at what such an accessor method does: i. Describe the current situation: Where is Mimi and what direction is she facing? Are there any eggs? ii. Call the method int getnrofeggshatched ( ). iii. Does calling this method change the situation in the world? e) What result did int getnrofeggshatched ( ) give? What does int mean? f) Can you create a situation in which the method int getnrofeggshatched ( ) returns the value 3? Tip: first place eggs in the world and then call hatchegg ( ). You have now seen that an accessor method returns information such as int or boolean, but shouldn t change the situation or state of an object. Challenge 1.4: Exploring the mutator method Our MyDodo has been programmed to do several things. You can let her do things (give her commands) by calling her mutator methods. a) Right-click on Mimi. You will see a list of all the things Mimi can do (in other words, which methods you can call), for example move ( ), and hatchegg ( ). Name one other method which makes Mimi do something. b) Drag Mimi to the centre of the world. Call Mimi s method void move ( ). Can you describe what the method does? i. Drag Mimi to the edge of the world, facing outwards. Call Mimi s method void move ( ) again. What happens now? Tip: to get rid of the pop-up dialogue, click either Reset or Run. ii. Using what you have just seen, match A, B and C in the flowchart in figure 18 to its corresponding code. Algorithmic thinking and structured programming (in Greenfoot) 16

Figure 18: Flowchart and code for MyDodo s move ( ) method Please read Theory 1.5: Classes and inheritance. Challenge 1.5: Inheritance We will now have a look at the methods which a MyDodo inherits from the Dodo family. a) Mimi is a MyDodo. All MyDodos are Dodos. Have a look at the class diagram on the right of the screen. Which other is-a relationships do you see? Name at least two. b) Mimi (who is a MyDodo), can do everything a Dodo can do. Right-click on Mimi (in the world). Click on inherited from Dodo. More methods appear, such as layegg ( ). Check that Mimi can execute the layegg (). c) Name two other methods which Mimi the MyDodo inherits from the Dodo class. d) In addition to Dodo methods, Mimi can do a few specific things that only MyDodo can do. Find a method which only MyDodo s have (and Dodos don t). We have now seen that Mimi (and all other MyDodos) inherit and thus can execute all Dodo methods. Please read Theory 1.6: The state of an object. Challenge 1.6: States Every object has a state. We will now have a look at how you can Inspect the states of objects. a) Drag Mimi into the world. Right-click on Mimi and select Inspect. What are her (int x and int y) coordinates? b) Investigate what the coordinates are at each of the corners. Draw in the coordinates in figure 19. The top-left corner has already been done for you. Algorithmic thinking and structured programming (in Greenfoot) 17

Figure 19: Coordinates in the world Please read Theory 1.7: Parameters and results. Please read Theory 1.8: Signatures. Challenge 1.7: Calling Accessor Methods In challenge 1.6 we saw that you can use Inspect to get information about Mimi s state. Accessor methods are used to return this information. Let s have a look at how this works. a) Right-click on Mimi. b) Which Dodo class methods return the coordinates of an object? Challenge 1.8: Using Parameters Let s have a look at a few examples of methods with parameters. a) Place Mimi somewhere in the middle of the world. Right-click on Mimi. Call the method jump ( int distance ). This method requires an int (whole number) as a parameter so that it knows how far (distance) Mimi must jump. Type in a small number and see what happens. b) Call the method jump ( int distance ) again. This time use a large number, such as 20, as the parameter. What happens? Can you explain why? c) What happens when you type something in that is not an int (whole number), such as 2.5? What error message do you get? What does this mean? (Tip: have a look at section Theory 1.13) d) If you type in a word as a parameter, instead of a number, you get an error message like in figure 20. Why does the error say something about a String? Figure 20: Error message when using text as a parameter Algorithmic thinking and structured programming (in Greenfoot) 18

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 ( already. ) method. Mimi can only lay an egg if there isn t an egg there a) Open MyDodo s code in the editor: Right-click MyDodo in the class diagram and select Open editor. b) Find the canlayegg ( ) method. Tip: use Ctrl+F. c) Have a look at the code for the boolean canlayegg ( ) method in figure 22. The flowchart in figure 21 on the left visualizes the algorithm. Fill in the missing gaps for A,B,C,D (in the flowchart) and E (in the code). d) Remove the comments in front of the code. e) In the code fill in E. f) Test your method. Algorithmic thinking and structured programming (in Greenfoot) 19

Figure 21: Flowchart for canlayegg ( ) method Figure 22: Code for canlayegg ( ) method Please read Theory 1.10: Java Documentation. Please read Theory 1.11: Modifying, compiling and testing programs. Please read Theory 1.12: Naming conventions. Challenge 1.10: Adding a new method turn180() We are now going to add a new method to MyDodo which makes Mimi turn 180 around. Figure 23: Flowchart and code for turn180 a) Have a look at the flowchart and its code. Fill in the missing gaps for A and B. b) Open the MyDodo class code in the editor. c) Write the code for the method turn180. d) Compile the code by pressing on the Compile button in the top-left part of the screen (see figure 24). Algorithmic thinking and structured programming (in Greenfoot) 20

If necessary fix any mistakes. Figure 24: Compile button e) Call your new method by right-clicking on Mimi and selecting void turn180 ( ). Test if it works as expected. Also test if the other methods still work correctly. In other words, check if the program as a whole still works as expected. f) Add comments above the turn180 ( ) method explaining what the method does, and what the initial and final situations are. Tip: Theory 1.10 explains how to add JavaDoc comments to code. Please read Theory 1.13: Errors. Challenge 1.11: Error messages The compiler is very picky. If you make a mistake in the code or forget something, the compiler will complain. It s useful to be able to recognize some common mistakes and error messages so that you can easily find the problem and fix it. Let s have a look at a few. a) Open the MyDodo class in the editor and find your method turn180 ( ). b) For each of the following, make the changes described, compile, and match the error message to the error in the code. Then fix the error in the code again. i. Delete a semi-colon ; behind turnright ( ); ii. Change the spelling of turn180 ( ) iii. Change turn180 ( ) into turn180 (5) iv. Remove the { after turn180 ( ) v. Remove the ) in turn180 ( ) vi. Remove the ( ) in turn180 ( ) Problem Error message ; expected ( expected method cannot be applied to given types invalid method declaration ) expected cannot find symbol 3. Fix the errors and test if the program still works as expected. Please read Theory 1.14: Printing to the console. Challenge 1.12: Printing text to the console Printing to the console (a separate window) can be useful for testing. a) Find the code for your turn180 ( ) method. Algorithmic thinking and structured programming (in Greenfoot) 21

b) Add the following print-to-console statement near the end of the method: System. out. println ( I just turned 180 degrees ); c) Execute your method by right-clicking on Mimi and calling turn180. Note: the console window may be hidden behind one of your other windows. You have now seen how to write code to print a text. Challenge 1.13: Printing variables to the console Printing to the console (a separate window) can be useful for testing. a) Find the code for MyDodo s jump ( ). b) The code doesn t correspond to the flowchart in figure 25. The difference is that the flowchart shows a print-to-console statement in the repeat-block. Figure 25: Example flowchart for printing text to the console c) Use System. out. println ( "moved " + nrstepstaken ); to add the print-to-console statement in the appropriate place in the code. d) Execute your method by right-clicking on Mimi and calling jump. Note: the console window may be hidden behind one of your other windows. e) Test your method using several different values. You have now seen how to write code to print both text and a variable to a console. Challenge 1.14: Printing coordinates to the console The mission is: Mimi walks across her row printing her coordinates to the console at each step. Algorithmic thinking and structured programming (in Greenfoot) 22

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

Reflection In this assignment you have become acquainted with Greenfoot. You have also been introduced to code. You adjusted code yourself, and practiced compiling and testing each small change that you made. One of the most important steps in becoming good at anything is to evaluate and reflect on what you did and how it went. Take one of the challenges in mind that you are proud of to reflect on. Result I know my solution works because... I am proud of my solution because... I could improve my solution by... Method My approach was good because... What I could do better next time is... Fill the following table with smileys indicating how things went. I can do it I did it a bit but didn t fully get it I didn t get it at all I can find my way around the Greenfoot environment I can explore which methods an object has and call (invoke) these I can explain the relationship between an algorithm, its flowchart and its code Given a method, I can find the code in the Greenfoot editor I can incrementally make changes to code I can add a method, compile, run and test I can recognize error messages Algorithmic thinking and structured programming (in Greenfoot) 24

Diagnostic Test Here are sample answers to the questions in the diagnostic test: 1. Which of the following is an int (more than one answer is possible): (a) getnrofeggshatched () (b) 4 (c) 3.2 (d) four (e) -3 (f) 0 (g) False 2. True or false? (a) boolean canmove () is an accessor method; (b) move () is an accessor method; (c) jump ( int distance ) is a mutator method. 3. Explain in your own words what a result type is. Give an example. 4. Match up numbers 1 through 6 in the flowchart in figure 26 with their corresponding parts of code. Figure 26: Code for MyDodo s move () method 5. Name a method that belongs to MyDodo but not to Dodo. 6. Have a look at the following class diagram: Figure 27: Class diagram Algorithmic thinking and structured programming (in Greenfoot) 25

(a) Fill the class diagram with the following class names: Kangaroo Lion ZooAnimal (b) Add the following methods to the corresponding superclass or subclasses: hop ( ) sleep ( ) roar ( ) eatmeat ( ) (c) Name all the methods which a Kangaroo can use. 7. What are the coordinates in the bottom-left corner? 8. Complete the table below. Method Result type Parameter type Belongs to class To be used by object getnrofeggshatched () none MyDodo MyDodo canmove () boolean jump () layegg () void turnleft () Dodo and MyDodo canmove () MyDodo getx () 9. Below are some names for a method which returns the number of eggs found. According to the naming conventions for methods names, which one is the best? (a) nrofeggs (b) nrofeggsfound (c) setnrofeggsfound (d) getnrofeggsfound 10. Below are some names for a method. According to the naming conventions for method names, which one is the best? (a) walk_to_egg (b) eggwalker (c) WalkToEgg (d) walktoegg (e) WALK_TO_EGG 11. Below are some names for a parameter indicating the number of eggs. According to the naming conventions for parameter names, which one is the best? (a) nr_of_eggs (b) EggCounter (c) nrofeggs (d) eggs (e) NR_OF_EGGS Algorithmic thinking and structured programming (in Greenfoot) 26

12. Here is code for a new method: public A movedown ( ){ turnright ( ) ; move ( ) ; B } The corresponding flowchart is: Figure 28: Flowchart for movedown () (a) Fill in A, B, C, D, E, F and G in the code and the flowchart. (b) What is the method s signature? Saving and Handing in You have just finished the assignment. Save your work! You will need this for future assignments. In the Greenfoot menu at the top of the screen, select Scenario and then Save. You now have all the scenario components in one folder. The folder has the name you chose when you selected Save As.... Handing in Hand in the following: Your name(s): you and your partner; Your code: The java file MyDodo. jav; Flowcharts: paste (photo s of) your flowcharts in a Word document; The reflection sheet: complete and hand it in. Algorithmic thinking and structured programming (in Greenfoot) 27