2: First Programs

What We Will Cover


Illuminations

Questions from last class or the Reading?

Quest and Lab Questions?

  • Lab 1: First Tutorial (9/5/17)
    Q1: Getting Started (9/7/17)
  • Please do not put spaces in folder names of zip files turned in for homework
  • The Java compiler has problems with spaces in folder or file names

Homework Discussion Questions

  1. Any problems you needed to solve while installing Java and Greenfoot?
  2. How hard are the tutorial labs in the textbook?

2.1: New Worlds and Beyond

Learner Outcomes

At the end of the lesson the student will be able to:

  • Create a new world for games or simulations
  • Create actors for the game world
  • Describe features of a Java class
  • Discuss how to document projects with a README.TXT file

2.1.1: Creating a New Scenario

  • During this lesson we will create a new scenario for a game or simulation
  • I suggest that you follow along on your own computer
  • If you cannot keep up then pay attention and we will have time at the end of the section
  • We start creating a new scenario by selecting New from the Scenario menu

    Creating a new scenario

  • Use the New Scenario dialog to save the scenario
    1. Choose a directory (folder) to save the scenario
    2. Enter a name for the scenario
    3. Press the Create button

    Remember where you saved the scenario so you can open it again.

    Creating a new scenario

  • Once saved, a new Greenfoot scenario appears

    Creating a new scenario

  • Notice that the file name becomes the name of the scenario

Try It: Create a New Scenario (2m)

  1. Start Greenfoot.
  2. Select New from the Scenario menu.
  3. Choose a directory (folder) to save the scenario such as the Desktop.
  4. Enter the File name "bugs" (without the quotes).
  5. Press the Create button

When finished, please help those around you.

Check Yourself

  1. To start a new scenario, press the menu item named ________.
  2. True or false: after starting a new scenario we give it a name.
  3. True or false: a new scenario has no classes shown in the class display.

2.1.2: Documenting with README.TXT

  • Whenever we start a new scenario, we should document our project
  • The traditional way to describe a project is to use a file named: README.TXT
  • The README.TXT file is important because it tells the reader, who does not know anything about your project, all that he or she needs to know to use your program
  • Thus, the README.TXT should include the purpose, version information, and instructions
  • Note that you will get points taken off of quests if you do not fill out the README.TXT file

Instructions for Creating a README.TXT file

  1. From the Scenario menu, select the Scenario Information option
  2. You will see a blank README.TXT file appear like the following

    Saving a scenario

  3. Fill in the information for the project

    New scenario page

  4. When finished, press the Close button

Try It: Document Your Scenario (3m)

  1. Press the Scenario menu button on the "bugs" scenario
  2. Select Scenario Information from the menu.
  3. Fill in the suggested information.

When finished, please help those around you.

Check Yourself

  1. True or false: Greenfoot automatically provides a blank README.TXT file when a new project is created.
  2. True or false: you will get points taken off quests if you do not fill out the README.TXT file.
  3. Of the following, the item that is NOT part of the README.TXT information is ________.
    1. AUTHORS
    2. PROJECT SIZE
    3. PURPOSE OF PROJECT
    4. USER INSTRUCTIONS

2.1.3: Scenario Classes

  • Remember that programming in Greenfoot and Java is based on objects.

    Object: a specific entity or thing.

  • In our scenarios we are modeling objects in a world, real or imaginary
  • There are two types of objects in a Greenfoot scenario: Worlds and Actors
    • A World holds actors: a "stage" for actors
    • An Actor can act: move, turn, etc.
  • The program code for an object is contained in a class

    Class: the general concept (type) of an object.

  • To make a game or simulation, we create subclasses of World or Actor

    Subclass: a class that inherits software elements from a superclass

  • For example, WombatWorld is a subclass of World and thus inherits (gets) many software elements from World

    Class diagram

  • Both Wombat and Leaf are subclasses of Actor and perform in the WombatWorld
  • The collection of classes for a scenario like the one shown above is called a class diagram
  • In the next sections we create a World and Actor for our new scenario

Check Yourself

  1. A specific entity or thing is known as an ________.
  2. True or false: a class is a specific instance of an object.
  3. A subclass inherits software elements from the ________.
  4. The relationship arrow (arrow for is-a realtionships) always points toward the ________.

2.1.4: Creating a World

  • When we start a new scenario, we have a default world named MyWorld
  • Usually, we want a different world name
  • To create a world for our scenario, we create a subclass of World
  • The following are the instructions for creating a new World subclass

Instructions for Creating a World Subclass

  1. Right-click on World in the class diagram and select New Subclass...

    Menu item to create a new world

    You will see a New World dialog like that shown below.

    New world dialog

  2. Set the worldType in a name for the new world.

    Note that the name must be a valid Java class name. A valid name can only have letters and numbers, not spaces or special characters. Also, you should start the name with a capital letter and capitalize every word for readability.

  3. Choose a suitable background image for the scenario.
  4. Press the Ok button.
  5. Set the new world subclass by selecting new WorldName(), where WorldName() is the name of our new world like new Bugworld()
  6. For housekeeping, remove old world classes no longer used

Compiling the World

  • Once you press the OK button, you will see a new World subclass in the class diagram

    New world subclass

  • Unless there is a problem, Greenfoot compiles the world automatically
  • If any of the classes have lines through them, we need to compile the code manually
  • To compile, open the World (BugWorld) source code and press the Compile button

    Compile button

  • If the class does not compile, we see a Next Error button instead
  • When we press the Next Error button, we see an error message near the error in the code like:

    Error example

  • We need to correct any errors found during compiling
  • After compiling correctly, we see a Greenfoot layout like the following...

    Default world size

Try It: Create a New World (2m)

  1. Right-click on World in the class diagram and select New Subclass...
  2. In the "New class name" field, type in the name "BugWorld" (without the quote marks).

    Please use the specified name if you want credit. Names are important in programming.

  3. Select a suitable background image such as "bricks2.jpg" in the backgrounds category.
  4. Press the Ok button and verify you see the new BugWorld class in the class diagram.
  5. Set the new world subclass by selecting new BugWorld().
  6. Remove the old MyWorld class by right-clicking on it and selecting Remove.
  7. Verify the scenario is compiled by verifying there are no slash marks through the BugWorld class. If not compiled, see Compiling the World above and get help as needed.

When finished, please help those around you.

Check Yourself

  1. To create a new World subclass, right-click the World and select ________.
  2. True or false: only one background image at a time is displayed in a World subclass.
  3. After we add a new World class like BugWorld, we always need to right-click the class and select ________ BugWorld().
    1. new
    2. compile
    3. reset
    4. run

2.1.5: Creating an Actor

  • Now that we have a world, we can add actors
  • Actors are the objects that we add to a world
  • For example, we can add a Bug actor to our scenario

  • To add actors, we first create subclasses of Actor
  • Adding an Actor subclass is like adding a World subclass
  • However, an actor inherits from the superclass Actor superclass instead of World
  • By subclassing Actor, our scenario actors inherit (possess) all the methods of the Actor superclass

Instructions for Creating an Actor Subclass

  1. Right-click on Actor in the class diagram and select New Subclass...

    You will see a New class dialog like that shown below.

    New class dialog

  2. Type in a name for the new actor.

    Note that the name must be a valid Java class name. A valid name can only have letters and numbers, not spaces or special characters. Also, you should start the name with a capital letter and capitalize every world for readability.

  3. Choose a suitable image for the actor.
  4. Press the Ok button.

Try It: Create a New Actor (2m)

  1. Right-click on Actor in the class diagram and select New Subclass...
  2. In the "New class name" field, type in the name "Bug" (without the quote marks).

    Use the specified name if you want credit. Names are important in programming.

  3. Select a suitable actor image such as "ladybug1.png" in the animals category.
  4. Press the Ok button and verify you see the new Bug class in the class diagram under Actor.
  5. Verify the scenario is compiled by verifying there are no slash marks through the Bug class. If not compiled, fix the problem and get help as needed.

When finished, please help those around you.

Check Yourself

  1. An actor is a subclass of ________.
    1. Actor
    2. Bug
    3. BugWorld
    4. World
  2. From the Actor superclass, a scenario actor inherits ________.
    1. images
    2. methods
    3. worlds
    4. numbers
  3. True or false: a Java class name may have spaces but not numbers.

Exercise 2.1: New Scenario

After completing the "Try It" exercises, it is time to save a copy of the scenario and reflect on what we have learned.

Specifications

  1. Complete the "Try It" exercise 2.1.1: Create a New Scenario.
  2. Complete the "Try It" exercise 2.1.2: Document Your Scenario.
  3. Complete the "Try It" exercise 2.1.4: Create a New World.
  4. Complete the "Try It" exercise 2.1.5: Create a New Actor.
  5. We will be adding to the scenario in future exercises so it is not time yet to submit the exercises.
  6. Take a minute and review in your mind the steps for creating a new scenario.

2.1.6: Summary

  • During this lesson we learned how to create a new game or simulation
  • We first created a new scenario by selecting New from the Scenario menu and using the dialogs
  • Then we discussed how to document your scenario using a README.TXT file
  • Whenever you start a new scenario, you should document your project
  • The README.TXT is the traditional way to describe the purpose and how to run the program
  • We then reviewed inheritance hierarchies and who Greenfoot scenarios have to types of objects:
    • World: the "stage" that holds actors
    • Actor: objects that can act such as move, turn, etc.
  • Then we discussed how to create a new World subclass
  • Essentially, you right-click on World in the class diagram and select New Subclass...
  • Then we just fill out the form for the new world
  • After creating a new world, you can add actors
  • Essentially, we right-click on Actor in the class diagram and select New Subclass...
  • Then we just fill out the form for the new actor

Self Reflection

Answer these questions to check your understanding. If you are not sure, then follow the links to the section and review the material.

  1. True or false: a new scenario has no classes shown in the class display. (2.1.1)
  2. True or false: every project should have a README.TXT file. (2.1.2)
  3. What is an object? (2.1.3)
  4. What is a class? (2.1.3)
  5. What is a subclass? (2.1.3)
  6. How do you create a new world? (2.1.4)
  7. How do you create a new actor for a world? (2.1.5)

2.2: Simple Movement and Rotation

Learner Outcomes

At the end of the lesson the student will be able to:

  • Make actors move in a Greenfoot world
  • Discuss method signatures and method bodies
  • Use the Greenfoot execution controls
  • Rotate an actor

2.2.1: Locating an Actor

  • After setting up a new world and actors, we need to move the actors in the world
  • A scenario world is organized into cells in an (x, y) coordinate system
  • Cells are often one pixel in size but can be larger as they were in the Wombat scenario
  • Movement is created by changing the location of the actor in the world
  • To change the location of an actor, we change its (x, y) coordinates

Actor movement

  • Notice that the upper left-hand corner is the origin (0, 0)
  • The x-coordinate is always positive and increases as the actor moves to the right
  • The y-coordinate is always positive and increases as the actor moves down
  • Changing both the x and y-coordinates causes the actor to move diagonally

Check Yourself

  1. The size of a scenario world is measured in ________.
  2. True or false: the coordinate system used by Greenfoot is the same as that used in algebra.
  3. The origin of the (x, y) coordinate system is located at the ________.
    1. upper left-hand corner of the window
    2. upper right-hand corner of the window
    3. lower right-hand corner of the window
    4. lower left-hand corner of the window
  4. True or false: in the coordinate system used by Greenfoot, locations shown in the window are always positive numbers.

2.2.2: Setting the Location

  • To change the actor location, we can work with methods inherited by our actor
  • A subclass of Actor, like our Bug, inherits all the public methods of the superclass
  • We can look at the inherited methods in Greenfoot by right-clicking on an object

    Actor menu

  • The method names give us a hint of what the methods do
  • A more thorough way to understand the methods is to look at the documentation for Actor
  • Notice the setLocation() method highlighted above
  • The method requires two arguments, which are the (x, y) coordinates of the actor
  • To change the location of the actor object, we can invoke the setLocation() method
  • For example, we could set the location to (200, 100)

    Calling mthod setLocation()

  • When we do, the actor jumps to the location (200, 100)
  • Note that the location is specified from the center of the actor

Check Yourself

  1. True or false: A subclass inherits all the public methods of its superclass.
  2. We find out what a method does by reading the API ________.
  3. To set the location of an actor we call the method ________ method.
  4. When we call the method setLocation(), we must include arguments for the coordinates ________.
    1. latitude, longitude
    2. r, Θ
    3. width, height
    4. x, y
    5. x, y, z

2.2.3: Introducing Source Code

  • Working with an object's menu is useful for understanding how to move actors
  • However, we need our actors to move by themselves
  • To have the actors move by themselves, we need to change their source code

What is Source Code?

  • Source code is the set of computer instructions for each software object
  • As an analogy, source code is like DNA in humans
  • The characteristics and abilities of a human are programmed in our DNA
  • Similarly, the characteristics and abilities of software objects are controlled by source code
  • We write the source code in the class defining how objects look and act
  • Each instance of a class then follows the instructions of its defining source code
  • Below is an example of source code for the Bug class

Initial Source Code for the Bug Class

Bug class source code

Changing the Source Code

  • Line 1 is an import statement
  • An import statement provides access to prewritten code called libraries
    • In this case, the "greenfoot" library
  • Line 3 through 8 are multi-line comments -- notes to programmers
    • We use comments to document blocks of code and to describe unusual code
    • Comments are ignored by the compiler and thus do not become commands to the computer
  • Line 9 is the first line of the class, which is known as a class declaration
    public class Bug extends Actor
    
  • Lines 10 through 19 contains the code that defines a class, known as the body
  • The body is always surrounded by curly braces: { }
  • Line 17 is a single line comment
  • All the text after the two slashes (//) and until the end of the line is a note to programmers
  • All Java class files have similar features:
    • Optional import statement
    • Optional comments
    • A class declaration
    • A class body
  • The code that we want to work with is in area of the class body known as the act() method
    public void act()
    {
        // Add your action code here.
    }
    
  • The act() method is important for every Actor subclass
  • All actions (behaviors) for every object start in the act() method

Changing the act() Method

  • The act() method is fundamental to the Greenfoot framework
  • All objects in the Greenfoot framework have this method including Actor and World
  • The first line of a method is known as the method signature
  • The last few lines -- the curly braces and anything between them -- is called the method body
  • We want to change the part that says: // Add your action code here.
  • Replace this comment with a call to the setLocation() method:
    setLocation(200, 100);
    
  • Now the code should look like this:
    public void act()
    {
        setLocation(200, 100);
    }
    
  • With this change, we can use the Greenfoot controls: Act, Run/Pause and Reset

Check Yourself

  1. True or false: the purpose of an import statement is to specify the use of prewritten code libraries.
  2. A note to a programmer in the source code is known as a ________.
    1. command
    2. comment
    3. declaration
    4. remark
  3. The Greenfoot method from which all actor behavior starts is named ________.
  4. The first line of a method is called the method ________.
  5. Inside the curly braces, where all the commands are placed, is the code area called the method ________.
  6. The method we program to control an actor's behavior is named ________.

2.2.4: Using the Greenfoot Execution Controls

  • Perhaps you have already tried the Greenfoot execution controls, which are the buttons:
    • Act: calls the act() method one time
    • Run: calls the act() method repeatedly (in a loop)
    • Pause (which appears after you press Run): stops the program execution
    • Reset: clears the world of objects
  • In addition, Greenfoot has a Speed slider control
  • The slider adjusts how often the act() method is called each second

    Execution controls

Animation Loop

  • Let us look at how Greenfoot controls the animation in a scenario
  • When the Run button is pressed, the Greenfoot framework continuously calls the act() method
  • The act() method is where you can update the location and make other commands to an actor
  • After the act() method completes, Greenfoot draws (renders) the image
  • Then Greenfoot waits a while before repeating the process
  • This sequence of events is known as an animation loop

    update,render,sleep

Check Yourself

  1. Pushing the Act or Run button calls the method named ________.
  2. To adjust the speed with which act() methods are called, move the ________.
  3. True or false: pressing the Reset button restarts the scenario.
  4. The method called by Greenfoot during the Update phase of the animation loop is ________.

2.2.5: Actor Movement Methods

  • When we run our actor objects with the following code, they all jump to one location and stay there
    public void act()
    {
        setLocation(200, 100);
    }
    
  • To make the actors move, we need to use other methods besides setLocation()
  • Remember the methods of the actor object menu:

    Actor move

  • Notice the method: move(int)
  • The move() method moves the actor the specified distance
  • For example:
    public void act()
    {
        move(1);
    }
    
    moves the actor one pixel forward in the direction it is facing
  • The instruction move(1) is called a method call
  • There are other methods for controlling movement as shown in the following table

Actor Methods for Controlling Movement

Method Description
getX() Return the x-coordinate of the actor's current location.
getY() Return the y-coordinate of the actor's current location.
move(distance) Move the actor the specified distance in the direction it is currently facing.
setLocation(x, y) Move the actor to the specified location.

Check Yourself

  1. To find the x and y-coordinates of an actor, call the method(s) ________.
    1. setLocation()
    2. getX() and getY()
    3. move()
    4. getLocations()
  2. To move the actor in the direction it is facing, call the ________ method.
  3. To move an actor 2 pixels forward in each scenario cycle, place the command ________ in the act() method.

2.2.6: Rotating and Turning Methods

  • We can make our actor turn to a specific direction by using the setRotation() method
  • The setRotation() method accepts a single parameter, which is the direction you want the actor to face
  • Zero degrees is to the east and the angle increases clockwise

    Degrees of a unit circle

  • For example, to make the actor face straight up use:
    setRotation(270);
    

Relative Rotation (Turning)

  • We can make our actor turn by using the method: turn()
  • For example, we can make our actor turn in place with:
    public void act()
    {
        turn(1);
    }
    
  • Also, we can combine moving with turning:
    public void act()
    {
        move(1);
        turn(1);
    }
    
  • We can turn our actors counter-clockwise with a negative number like:
    turn(-1);

Actor Methods for Controlling Direction

Method Description
getRotation() Return the angle of the direction that this actor is facing, where zero degrees is to the east and the angle increases clockwise.
setRotation(angle) Set the angle that the actor is facing, where zero degrees is to the east and the angle increases clockwise.
turn(amount) Turn this actor from its current direction by the specified amount in degrees.
turnTowards(x, y) Turn this actor towards the specified (x, y) coordinate.

Command Sequence

  • Within a method, code runs from top to bottom, left to right in a continuous sequence
  • Sometimes it is hard to see this sequence because the animation loop displays the updated graphics only after the act() method finishes
  • For example, we place the following sequence of instructions into the act() method:
    public void act()
    {
        move(30);
        turn(45);
        turn(-45);
        move(-30);
    }
    
  • When we run the code nothing seems to happen -- can you see why?
  • To show the sequence, we call the delay() method after each command
  • The delay() method causes Greenfoot to delay the scenario by a number of time steps
    public void act()
    {
        move(30);
        Greenfoot.delay(10);
        turn(45);
        Greenfoot.delay(10);
        turn(-45);
        Greenfoot.delay(10);
        move(-30);
        Greenfoot.delay(10);
    }
    
  • Method delay() is rarely useful as it delays the entire scenario
  • Thus other actors stop until all the delays are finished for one actor before proceeding to the next actor
  • We can see the delay() effect by adding two bugs to the scenario

Check Yourself

  1. If we set the actor facing zero (0) degrees, this is the same as the compass heading ________.
  2. To get the current heading of an actor, call the method ________.
  3. To set the current heading of an actor, call the method ________.
  4. To turn 5 degrees counter-clockwise, use the method call ________.
    1. turn(-5)
    2. turn(5)
    3. setRotation(-5)
    4. getRotation(5)
  5. True or false: the default behavior for program statements within a method is to execute sequentially.

Exercise 2.2: Moving and Turning (5m)

In this exercise, we make our Bug actors change location and turn by changing source code in the act() method.

Specifications

  1. Start Greenfoot and reopen the bug scenario from the last exercise.

    If you do not still have the scenario, you can recreate it from exercise 2.1.

  2. Open the source code editor of the Bug class by right-clicking on the Bug class and selecting Open editor.
  3. Find the act() method and change the method by adding:
    setLocation(200, 100);
    

    For more information see section: 2.2.3: Introducing Source Code.

  4. Create two or more bugs and then press the Run button.

    Notice how the bugs jump to a single location. Since the bugs all jump to the same location, they look like a single bug. We would like each bug to move independently.

  5. Change the act() method to:
    move(1);
    

    For more information see section: 2.2.5: Actor Movement.

  6. Create two or more bugs and then press the Run button.

    Notice how the bugs all move the same.

  7. Change the act() method to:
    turn(2);
    

    For more information see section: 2.2.6: Actor Rotation and Turning.

  8. Create one or more bugs and then press the Run button.
  9. Change the act() method to:
    move(2);
    turn(5);
    

    This is an unusual motion for a bug but gives you some idea how you can combine commands to create more complex movement.

  10. Save a copy of your scenario to upload to Canvas later as part of the next lab.

    We will be adding more code to these files in subsequent exercises, so it is not time to submit them to Canvas yet. However, it is a good idea to have a backup copy in case of problems later in development.

When finished, please help those around you.

2.2.7: Review

Answer these questions to check your understanding. You can find more information by following the links after the question.

  1. True or false: the coordinate system used by Greenfoot is the same as that used in algebra. (2.2.1)
  2. The origin of the (x, y) coordinate system is located at: (2.2.1)
    1. The upper left-hand corner of the window
    2. The upper right-hand corner of the window
    3. The lower right-hand corner of the window
    4. The lower left-hand corner of the window
  3. True or false: in the coordinate system used by Greenfoot, locations shown in the window are always positive numbers. (2.2.1)
  4. What is a subclass and what does it inherit? (2.2.2)
  5. True or false: A subclass inherits all the public methods of its superclass. (2.2.2)
  6. Which method do you change in an actor subclass? (2.2.3)
  7. True or false: the act() method is present in all Greenfoot actor classes. (2.2.3)
  8. True or false: the Act button calls the act() method repeatedly. (2.2.4)
  9. True or false: the getX() method returns the current y coordinate of an actor. (2.2.5)
  10. Which of the following statements moves an actor one cell in the direction it is facing? (2.2.5)
    1. move(1);
    2. move(10);
    3. move(-1);
    4. move(-10);
  11. True or false: the setRotation() method turns the actor to face in a particular direction. (2.2.6)
  12. True or false: the getRotation() method returns the current direction that an actor is facing. (2.2.6)

2.3: Dealing with World Edges

Learner Outcomes

At the end of the lesson the student will be able to:

  • Describe the result of a method call with a Boolean return type
  • Use simple if statements
  • Correct simple computer program errors

2.3.1: At the World's Edge

  • When we make our actors move, they get stuck when they reach the edge of the world
  • We want to change this behavior so that our actors notice they reach the edge of the world and turn around
  • To detect the world's edge, we call the following Actor method

Actor Method for Detecting the World's Edge

Method Description
isAtEdge() Detects whether the actor has reached the edge of the world.

Detecting a World's Edge

  • The above method tests to see if an actor is at the edge of the world or beyond
  • The method's signature is:
    boolean isAtEdge()
  • The return type boolean means the method returns either true or false
  • Calling methods that have a boolean return value is like asking a question
  • If the actor is at or beyond an edge, the method returns true (Yes!)
  • If the actor is not at an edge, the method returns false (No!)
  • Thus, we can use this method to detect if an actor is at the edge of the world

Check Yourself

  1. True or false: the isAtEdge() method returns true if the actor is near the edge of the world; otherwise it returns false.
  2. The type that returns either true or false is known as a(n)________.
  3. True or false: when a method returns true or false, calling the method is like asking a question.

2.3.2: Simple if Statements

  • So far, all our programs have simply executed a list of instructions
  • We arrange our command statements in a particular order to get the result we want like
    move(2);
    turn(5);
    
  • When the program reaches the end of the list of instruction, it ends for this animation loop
  • To create a different set of actions, like for when an actor reaches the edge of the world, we use an if-statement
  • An if statement has two parts: a test and a body
  • The body can have zero or more statements
  • The statements in the body execute if and only if the test condition evaluates to true
  • If the test condition evaluates to false, the computer skips the code
  • Syntax:
    if (test)
    {
       statement1
       statement2
       ...
    }
    
  • Where:
    • test: the test condition that evaluates to true or false
    • statementX: the sequence of statements to execute depending on the test condition
  • For example:
    if (isAtEdge())
    {
        turn(17);
    }
    
  • The test in the above example calls the isAtEdge() method
  • If the isAtEdge() method returns true then the turn() is executed
  • Otherwise, the turn() is not executed

Diagram of if Statement Operation

If statement operation

Making Decisions

Try It: Add an if-statement (2m)

  1. Start Greenfoot and reopen the bug scenario from the last exercise.

    If you do not have the scenario, download, unzip and open this scenario link.

  2. Open the editor for Bug
  3. Change the act() method by adding an if-statement as shown in the code below.
  4. Test your code by adding a Bug to the scenario and pressing the Run button

    The bug should turn when it reaches the edges of the window. If you have problems, please ask a classmate or the instructor for help.

  5. Save a copy of your scenario to upload to Canvas later as part of the next lab.

    We will be adding more code to these files in subsequent exercises, so it is not time to submit them to Canvas yet. However, it is a good idea to have a backup copy in case of problems later in development.

When finished, please help those around you.

Example Program With an if Statement

Source code with if statement

Formatting an if-statement

  • We want our code to look professional so we need to discuss how to format if-statements
  • For clarity:
    • Write the if (test) on a different line than the body
    • Indent statements 4 spaces within the curly braces
  • The reason for indenting is to show where the flow may change
  • We can automatically indent our if-statements by clicking the Edit menu and then choosing Auto-layout
  • We can see an example of an if statement in the following example

Check Yourself

  1. To execute statements only when a certain condition is true, use an ________ statement.
  2. True or false: the computer makes a test to decide whether or not to execute instructions inside an if-statement.
  3. True or false: a test condition must evaluate to either true or false.
  4. Always indent the parts of an if-statement between the ________.

2.3.3: Errors and Debugging

  • As you develop programs, you will make errors
  • These errors are known euphemistically as "bugs" (See also: First Computer Bug)
  • Often the error is because we left out a character or misspelled a word
  • In programming, one small mistake means the program does not work
  • Usually, the compiler finds the error and reports the problem to us
  • For example, if we leave a semicolon off the end of a line we might see:

    Error message

  • The error message is in the black box to the lower right of the error
    ';' expected
  • Notice that the Greenfoot editor highlights the error by underlining it with a dotted red line
  • Then we need to hover over or click on the error to see the error message
  • However, sometimes the error occurs on a line before or even after the reported problem
  • Thus, we start by looking at the reported error location but sometimes we have to look before or after the error
  • Also, we may get multiple errors reported for a single mistake
  • Thus we should always fix the first error and recompile before fixing subsequent errors

Example Code with Three Errors Reported for a Single Problem

Common Errors

  1. Missing semicolon (;)
  2. Misspelled words in commands
  3. Missing or unmatched parenthesis
  4. Missing or unmatched curly braces
  5. Comments without comment symbols

Check Yourself

  1. True or false: a mistake in program code is sometimes blamed on bugs.
  2. True or false: the compiler finds many errors such as missing characters or misspelled words.
  3. True or false: if the compiler finds an error, Greenfoot will highlight the error and display the error message.
  4. True or false: all error messages are easy to understand.

2.3.4: Printing to a Terminal (Console) Window

  • Java provides two built in methods to display text data in a terminal window
  • These methods are print() and println()
  • Greenfoot sends the information to the terminal window
  • To call (invoke) those methods, we must add the words "System.out." in front of the method calls
    • We will discuss why we add these words in future lessons
  • The difference between the two methods is that:
    • print() leaves the cursor positioned after the last character
    • println() positions the cursor on a new line
  • The cursor position determines where the next character is displayed
  • For example:
    System.out.print("Hello, ");
    System.out.println("world!");
    
  • The data to display is passed to the method within the parenthesis

Printing as a Debugging Tool

  • Some types of errors, know as logic errors, cannot be detected by the compiler
  • We can find these errors only by watching how our programs run
  • However, sometimes it is not clear which line of code may cause a problem
  • For example, suppose we had the following act() method in Bug, which has an error
    // This act method has a logic error
    public void act()
    {
        if (isAtEdge())
        {
            move(3);
            turn(17);
        }
    }
    
  • How many people see the error?

Checking for an Error

  • The code compiles correctly and Greenfoot does not report any errors
  • However, when we can place a bug into our world and press the Run button, the bug does NOT move
  • To find the problem, we must trace the code in the order the statements execute
  • Every Greenfoot class starts executing in the act() method
  • After the act() method is called by Greenfoot, the computer executes all the statements in order (sequentially)
  • To help us trace the flow we can add a print statement to the act() method like:
    // This act method has a logic error
    public void act()
    {
        System.out.println("In Bug act");
        if (isAtEdge())
        {
            move(3);
            turn(17);
        }
    }
    
  • Now when we run our program, we see messages in the terminal window
  • This lets us know that the act() method is executing
  • Sometimes the terminal window get too cluttered with messages
  • When this happens, we can clear the text using the Ctrl-k keys
  • Also, we can reduce the number of messages by tracing using the Act button instead of the Run button

Continuing the Trace

  • Now that we know the act() method is executing we continue the trace by moving the print statement
    // This act method has a logic error
    public void act()
    {
        if (isAtEdge())
        {
            System.out.println("In if statement");
            move(3);
            turn(17);
        }
    }
    
  • Now when we run our program, we do NOT see messages in the terminal window
  • This lets us know that the logic error is before the current print statement but after our previous print statement
  • We have "bracketed the problem" and identified where it is occurring
  • How many people see the problem now? Click to show answer

Remarks on Print Debugging

  • Debugging with print statements is a common technique
  • However, more powerful tools exist which we will explore as we develop our coding skills
  • Even though more powerful tools exist, print debugging is still useful
  • For instance, better tools are not always available but printing is almost universal in programming languages

Check Yourself

  1. To print text data in a terminal window, call the method System.out.print() or ________.
  2. True or false: by using println() rather than print(), a new line is added to the text displayed
  3. True or false: one use for print(), or println(), is to help trace code by displaying tracing messages.

Exercise 2.3: Debugging Errors

In this exercise we practice finding and fixing errors.

Specifications

The following class was written by a person in a hurry. During the writing process a large number of errors were made. You need to find and correct the errors while still allowing the BadBug to move and turn at the edge. Hint: the errors are all in the act() method.

Code for the BadBug Class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import greenfoot.*;

/**
 * A very badd bug.
 *
 * @author B. A. Ware
 * @version 1.0
 */
public class BadBug extends Actor
{
    /**
     * Act - do whatever the BadBug wants to do. This
     * method is called whenever the 'Act' or 'Run'
     * button gets pressed in the environment.
     */
    public void act()
    {
        if (isAtEdge)
        {
            turn();
        move()
    }
}
Part A: Peer Review (3m)
  1. Find a partner for this exercise and create a text file named errors.txt
  2. Add a comment at the top of the file that contains the name of the person(s) with whom you reviewed the code, like:
    // Reviewed with Emma Programmer
    
  3. With your partner, review the program, finding and listing in your errors.txt file the line number and description of as many errors as you can within 3 minutes.
  4. Submit your list of errors to Canvas as part of next weeks lab (Lab 2).
Part B: Syntax Errors (5m)

In this step, we correct all the errors in the BadBug file.

  1. Start Greenfoot and reopen the bug scenario from previous exercises.

    If you do not have the scenario, download, unzip and open this scenario link. While this scenario link does not have all work from previous exercises, it will allow you to complete this exercise.

  2. Create a new subclass of Actor named BadBug.

    Choose any image you want for BadBug but use the correct name.

  3. Open the editor for BadBug and replace the existing code with the code listed above.
  4. Find and correct the syntax errors reported by the compiler.

    Note: all the errors are in the act() method.

  5. Use print statements to trace the code as needed.
  6. Save your scenario to upload to Canvas as part of the next lab (Lab 2).

Be prepared to answer the Discussion Questions when called upon and then help those around you.

Discussion Questions

  1. Did having someone review your code help find errors?
  2. What was the cause of the message after the move() method, "missing semicolon"?
  3. What was the cause of the message at the last brace, "reached end of file while parsing"?
  4. Did the list of errors reported by the compiler change dramatically as you corrected each one?
  5. Were the errors always on the line reported by the compiler?
  6. Did the compiler always find errors in the order in which the program code was listed?

2.3.5: Summary

  • The default behavior of program code is to execute one statement after another in sequence
  • Sometimes we want to execute some statement only under certain conditions
  • For example, if an actor reaches the edge of a screen we want it to turn
  • Java has a statement for conditional execution called the if-statement
  • An if statement has two parts: a test condition and a body
  • For example:
    if (isAtEdge())
    {
        turn(17);
    }
    
  • The parenthesis after the word if contains the test condition
    isAtEdge()
  • The method call isAtEdge() returns either true or false
  • If the method returns true, then the body of the if-statement executes:
    {
        turn(17);
    }
    
  • If the method returns false, then the program skips the body of the if-statement
  • Using if-statements, you can add more intelligence to your actors
  • As you develop programs you make mistakes and one small mistake means the program does not work
  • The process of correcting the mistakes is known euphemistically as "debugging"
  • Oftentimes the compiler finds the error and reports the problem with an error message
  • You can correct errors by carefully reviewing the line reported to contain an error
  • Sometimes you will need to examine lines before or after the reported line as well

    Multiple errors

  • To find logic errors, you must run your program and watch how it runs
  • For example, your code may compile but the character does not move
  • To find logic errors you must trace your code in the order the statements execute
  • One tool to help trace is printing to a terminal (console) window
  • By inserting print statements in your code, you can bracket the lines with the error
  • Bracketing the problem makes it easier to understand logic errors

Self Reflection

Answer these questions to check your understanding. If you are not sure, then follow the links to the section and review the material.

  1. True or false: the isAtEdge() method returns true if the actor is at the edge of the world; otherwise it returns false. (2.3.1)
  2. True or false: the default behavior for program statements is to execute sequentially. (2.3.2)
  3. True or false: If you want to write instructions that are executed when a certain condition is true, you can use an if-statement. (2.3.2)
  4. True or false: the computer makes a test to decide whether or not to execute instructions inside an if-statement. (2.3.2)
  5. The names of the parts of the if-statement that follows are: (2.3.2)
    if (isAtEdge())
    {
        turn(17);
    }
    
    1. statement keyword: ________
    2. test condition: ________
    3. part executed if test is true: ________
  6. True or false: a test condition must evaluate to either true or false. (2.3.2)
  7. What part of an if-statement is indented? (2.3.2)
  8. True or false: a mistake in program code is sometimes blamed on bugs. (2.3.3)
  9. True or false: all errors are found by the compiler. (2.3.3)
  10. Errors in the way a program works that are not found by the compiler are known as ________ errors. (2.3.4)
  11. What statement is used to print to a terminal (console) window? (2.3.4)
  12. True or false: one use for printing messages to the terminal window is to displaying tracing messages. (2.3.4)

2.4: Exploring Source Code

Learner Outcomes

At the end of the lesson the student will be able to:

  • Declare variables and assign values to variables
  • View the methods of a class in source code
  • Define the parts of a method declaration
  • Make calls to methods of the Actor superclass

2.4.1: Introduction to Variables

  • One of the most important features of computers is memory
  • Computers store values like numbers, text, images, and sounds in its memory
  • With the stored data, computers do calculations, make changes and store the results until needed
  • For example, we may want to store an image for an actor or remember the x-coordinate of the actor
  • To remember something in Java, we use a variable
  • variable: the name of a place to store data in a computer's memory

Variable Declaration

  • The following statement declares a variable:
    private int x;
    
  • We place the variable declaration statement inside the class like:
    public class Bug extends Actor
    {
        private int x;
    
  • When we declare a variable we tell the computer to set aside space to store data in its memory
  • Notice that a variable declaration has these parts:
    • private: keeps access inside the class
    • int: the type of data the variable will store, integer values in this case
    • x: the name of the variable, which we make up while coding
Data Type
  • The data type of a variable is like the return type of a method -- it says the type of data
  • Like human memory, a computer must encode information before storage
  • A computer needs to know what type of data it will store when preparing to store a variable
  • The data type tells the computer how to encode the data and how much space to set aside
  • A commonly used numeric data type is int which is shorthand for integer
  • An int is a whole number with no fractions or decimal points
  • Variables can store many other types of data including text, images and sound
Naming
  • The other part of a variable declaration is the name
  • Names are made up by the programmer and should indicate what data the variable stores
  • The basic rules for naming a variable are simple:
    1. Names are any combination of letters, digits and underscore characters
    2. Names cannot start with a number

Assignment Statement

  • After declaring a variable, we give it a value with an assignment statement
  • An assignment statement sets the value stored in a variable
    x = 42;
    
  • The equals (=) sign is how you assign values to variables
  • The value to assign is on the right-hand side of the equals (=) sign
  • The name of the memory location (variable) in which to save the data is on the left-hand side of the equals sign
  • Notice that we can declare a variable and assign it a value in one statement:
    int x = 42;
    
  • The value to assign is computed on the right-hand side of the equals (=) sign
  • The variable declaration is on the left-hand side of the equals sign
  • We can see the value of x by printing it to a terminal window
    int x = 42;
    System.out.println("x=" + x);
    
  • Now when we run our program we will see the value of the variable "x"

Variables by Analogy

  • We can think of variables as boxes made of computer memory
  • A variable is just like a box that can hold a single thing
  • We need a way to tell one box from another so we give it a name
  • As we discussed, we can make up almost any name we want for the variable
  • For example, we declare a variable "a"
    int a;
    
  • When we first declare a variable the box is empty but has a name

    Empty box labeled a

  • Storing values in a variable is like putting items in a box
  • For example, we assign the variable "a" the value 1
    a = 1;
    
  • We can think of the above statement as putting the value 1 in the box with the variable name "a", like the one shown below (image source: David Goodger)

    value 1 in box a

  • We put names on a box
  • We put values inside of boxes
  • When we want to see the value inside a box we look at it with code like:
    System.out.println(a);
    
  • If we change the value of a variable, we are putting a new value in the same box, like:
    a = 2;
    

    value 2 in box a

  • Making a new variable and assigning one variable to another makes a copy of the value and puts it into the new box:
    int b = a;
    

    value 2 in box bvalue 2 in box a

  • We now have two different boxes that have independent values

Try It: Code Variables (4m)

  1. Start Greenfoot and reopen the bug scenario from the last exercise. If you do not have the scenario, download, unzip and open this scenario link.
  2. Open the source code editor of the Bug class by right-clicking on the Bug class and selecting Open editor.
  3. Add an integer variable named speed to the class
    private int speed = 1;
    
  4. In the act() method, replace the call to move(2) with:
    move(speed);
    
  5. Inside the if-statement, change the amount of turn() as shown and add the following statements:
    turn(80);
    speed = speed + 1;
    System.out.println("speed=" + speed);
    
  6. Verify your code against the following and then run a Bug in the scenario to observe its behavior.
  7. When finished, make sure you know the answers to the following Check Yourself questions and then help other students.

Listing of act() Method

act with variable

Check Yourself

  1. The name of a location to store data in a computer's memory is known as a(n) ________.
  2. True or false: remembering data is rarely important when processing information.
  3. To specify the type of data stored in a variable, variable declarations include a(n) ________ ________.
  4. True or false: the bug speeds up every time it hits the edge of the scenario.

2.4.2: Methods Explained

  • Methods are code containers or code packages
  • More technically:

    Method: a sequence of programming instructions packaged as a unit.

  • Methods define the behavior of the instances (objects) of a class
  • To interact with an object, we invoke (or call) its methods
  • To gain a clear understanding of methods, we will first use methods already built into Greenfoot
  • Later we will write our own methods to create more complex scenarios

Greenfoot API Methods

  • We have been calling methods such as move() and turn()

    Actor move

  • These methods are inherited from the Actor superclass
  • The Greenfoot Application Programming Interface (API) contains a list of all Greenfoot methods
  • We will need to refer to the Greenfoot API often to make the most of our scenarios
  • The Greenfoot API is located at: http://www.greenfoot.org/files/javadoc/
  • We can access the Greenfoot API from our scenario's Help menu as well
  • Notice that methods are not limited to movement alone
  • Methods can give us information about an object such as its direction, size and position

Activity: Navigating the API (4m)

Open the Greenfoot API and take a few minutes to see how to navigate among the various web pages. Then be prepared to answer the following questions when called upon.

Check Yourself

  1. The Greenfoot API has ________ classes.
    1. 5
    2. 6
    3. 7
    4. 10
  2. The class that describes an object that exists in the Greenfoot world is known as a(n) ________.
  3. The name of the Actor method that is called by the greenfoot framework to give actors a chance to perform some action is ________.
  4. True or false: the Actor class has more than 10 methods.
  5. True or false: to get a detailed description of a method in the Method Summary section, click or tap the method name link.

2.4.3: Method Signatures and Return Types

  • Every method in the Greenfoot API has similar parts

    Parts of a method

  • The first part is the return type, which specifies what the method returns
  • The second part is a name given to the method
  • The last part is the parameter list
  • Together they make up the method signature

Return Types

  • Notice that the method "setDirection" has the word void in front of it
  • The word in front of a method name tells us what type of data comes back from the method call
  • The word void, meaning "nothing", tells us that no data returns from the method
  • On the other hand, the method getX() returns int data, where int is short for integer
    int getX()
    
  • Thus the type of data that comes back from calling the getX() method is an integer (whole number)
  • Other methods return other types of data
    GreenfootImage getImage()
    World getWorld()
    
  • The first returns a GreenfootImage object and the second returns the current World object
  • We can store the data returned from these method calls in variables as well
    GreenfootImage myImage = getImage();
    World myWorld = getWorld();
    

Method Names

  • All methods have a name that should describe what the method does

    Method name: A name used to invoke (call) the method's statements (commands).

  • By right-clicking on an instance of a class, we get a list of method names

    Actor move

  • We see that the names of methods give a brief description of what the method does
  • For more detailed information, we look up the method name in the Greenfoot API

    http://www.greenfoot.org/files/javadoc/

Parameter Lists

  • Every method has a parameter list, which is listed inside the parenthesis
  • Even methods that accept no parameters have an empty parameter list
  • Thus, we always see parenthesis when we see a method
  • Notice the setDirection() method of an Actor object
    void setDirection(int direction)
  • The words inside the parenthesis are for a parameter
  • A parameter is a way to send data to the method that it needs to run
  • The word int (which is short for integer) is the type of the parameter
  • The word direction is a name that gives us a hint what the parameter is used for
  • Every parameter has at least two words like this: int direction
  • When we invoke the setDirection() method, it needs a single parameter value
  • Thus, to call the method in source code we would write something like:
    setDirection(90);
    
  • The data or value we supply to a method with a parameter is called an argument

Method declarations

Example Method from "Save the World"

  • We can see an example of a method added to our World subclass
  • First we open the current World subclass, like BugWorld
  • Look at the code and notice how many lines exist
  • Next we populate the scenario and invoke the Greenfoot "Save the World" function
    Controls ⇒ Save the World
    
  • Now notice the new method in the World subclass named prepare
    private void prepare()
    {
        // variables and object instantiation here
    }
    
  • Also notice how the prepare method is called
    public BugWorld()
    {
        // Create a new world with 600x400 cells with a cell size of 1x1 pixels.
        super(600, 400, 1);
        prepare();
    }
    
  • After creating the world, the prepare() method is called

Activity: Method Signatures (5m)

Method Signature Method Name Return Type Number of Parameters

Check Yourself

  1. The return type of the following method signature is ________.
    int getX()
    
  2. The return type of the following method signature is ________.
    World getWorld()
    
  3. The names of the parts of the method signature void setDirection(int direction) are:
    1. return type: ________
    2. method name: ________
    3. parameter list: ________
  4. True or false: a parameter list may be empty, meaning there is no code between the parenthesis.
  5. True or false: parameters always have a type, unless the list is empty.
  6. Using a method is known as ________ the method.
  7. When calling a method with a parameter, you must supply the necessary ________.
  8. Of the following, the method signature is ________ and the method call is ________.
    1. getWorld()
    2. World getWorld()

2.4.4: Documenting Our Work

  • Whenever we create a new subclass, we should document our work
  • The first step in documenting our work is to fill out the README.TXT
  • See lesson 2.1.2 for how to fill out the README.TXT file
  • After filling out the README.TXT file, we document each class by opening the source code and filling in some simple information
  • As an example, the following is the initial source code for the Bug class

Initial Source Code for the Bug Class

Bug class source code

Leaving our Imprint

  • At the top of the class is a block comment automatically supplied by Greenfoot
    /**
     * Write a description of class Bug here.
     *
     * @author (your name)
     * @version (a version number or a date)
     */
    
  • To document our code we simply write a brief description of the class
  • Then we simply fill in the information for the parentheses: our name and a version number or date
  • The following is an example of a filled in comment for the same class
    /**
     * Our main character.
     *
     * @author Ed Parrish
     * @version 10/23/2015
     */
    
  • We could leave a version number rather than a date if we prefer to use version control
  • However, a date is easier when you are new to programming

Why Document Our Work?

  • Do remind us what we were doing
  • To put our name on our work
  • To put our date on our work
  • To get full credit on our assignments

Exercise 2.4: Reflection (2m)

Turn off your computer monitor and take two minutes and reflect quietly on what you have learned about code and how to apply code to making scenarios. Be prepared to share what you have learned.

There is nothing to turn in for this exercise.

2.4.5: Summary

  • Oftentimes we ned to remember information in our programs
  • To remember something in Java, we use a variable
  • variable: the name of a place to store data in a computer's memory

  • As an example, we looked at the variable declaration:
    int x;
  • Notice that a variable declaration has two parts:
    • int: the type of data the variable will store, integer values in this case
    • x: the name of the variable, which we make up while coding
  • To give the variable a value, we use an assignment statement like:
    x = getX();
    
  • In addition, we can declare a variable and assign it a value in one statement:
    int x = getX();
    

Methods

  • We also discussed methods in this lesson
  • Methods are a sequence of programming instructions packaged as a unit
  • Every method has a name, return type and parameter list

    Parts of a method

  • The first part is the return type, which specifies what the method returns
    • If the method returns nothing, we use the word void.
    • If the method has a boolean return type, it can return either true or false.
  • The name is chosen by the programmer as a hint on the action the method performs
  • The last part is the parameter list, which is data that the method needs to run
  • Each parameter has a data type and a name
  • If no parameters are needed, then the parenthesis are empty

Self Reflection

Answer these questions to check your understanding. If you are not sure, then follow the links to the section and review the material.

  1. The name of a location to store data in a computer's memory is known as a(n) ________. (2.4.1)
  2. What are the two parts of a variable declaration? (2.4.1)
  3. What symbol is used to indicate an assignment statement? (2.4.1)
  4. True or false: for an object to perform an action, we call (invoke) a method. (2.4.2)
  5. To find detailed information about a Greenfoot method, we look in the Greenfoot ________. (2.4.2)
  6. True or false: every method has a return type. (2.4.3)
  7. True or false: the return type of a method specifies what a method call will accept. (2.4.3)
  8. What is the purpose of a method name? (2.4.3)
  9. True or false: every method has a parameter list, though some lists may be empty. (2.4.3)

Wrap Up

Due Next:
Q1: Getting Started (9/7/17)
Lab 2: Improving the Crab (9/12/17)
Q2: First Program (9/14/17)
  • When class is over, please shut down your computer
  • You may complete unfinished lesson exercises at any time before the due date.
Home | Canvas | Schedule | Syllabus | Room Policies
Help | FAQ's | HowTo's | Links
Last Updated: September 09 2017 @15:08:28