4. Finishing the first program

What We Will Cover


Illuminations

Questions from last class or the Reading?

Homework Questions?

  • A3: Methodical Improvement (2/29/12)
  • In your team, review each others programming projects from the last assignment
  • Select one good example project to share with the rest of the class using the criteria:
    1. Completeness
    2. Person has not shared before
    3. Extra features or creativity

Matching Relationships Game

Match the questions with the answers. Use the box on the left to write your choice. Then click on the Answers box to see if your answers are correct.

1. Less than    a. ==
2. Assignment    b. =
3. Less than or equal    c. <=
4. Not equal    d. >=
5. Greater than    e. >
6. Greater than or equal    f. <
7. Equal    g. !=

4.1: Setting up a Scenario

Learner Outcomes

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

  • Prepare scenarios automatically
  • Code constructors
  • Construct new objects programmatically

4.1.1: World Initialization

  • We we start our scenarios, we must place actors manually
  • It would be better if the actors were placed automatically
  • There is one part of the scenario that is created automatically -- the world
  • For instance in the bug scenario, BugWorld is created automatically
  • We can use this property to set up the initial state of our scenario
  • If you look at the BugWorld source code, you will see something like the following
    • I shortened some of the comments so they would fit in the page

Example BugWorld Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import greenfoot.*;  // Greenfoot framework

/**
 * Write a description of class BugWorld here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class BugWorld  extends World
{

    /**
     * Constructor for objects of class BugWorld.
     */
    public BugWorld()
    {
        super(600, 400, 1);
        prepare();
    }

    /**
     * Prepare the world for the start of the program.
     * That is: create the initial objects and add them
     * to the world.
     */
    private void prepare()
    {
    }
}

4.1.2: The World Constructor

  • The first line is the import statement, which allows access to the Greenfoot framework
    import greenfoot.*;  // Greenfoot framework
    
  • There are several lines of comments that the compiler ignores
  • Then comes the class header and another comment block
  • Then comes the part that controls how the world starts -- the constructor:
    public BugWorld()
    {
        super(600, 400, 1);
        prepare();
    }
    
  • The purpose of a constructor is to prepare a new object for use
  • A constructor is coded like a method but there are some differences
  • By looking, can you identify two differences? answer
  • The first line in the body of the constructor sets up the size of the world
  • Notice the method call to prepare() in the constructor
  • We can add code to either the constructor or the prepare() method to automatically create actors
  • For example:
    private void prepare()
    {
        addObject(new Bug(), 150, 100);
    }
    
  • The code automatically creates a new crab and places it in the specified (x, y) location
  • We have two new things here:
    1. the addObject() method
    2. the new statement
  • We will consider both in the following sections

Check yourself

  1. True or false: the purpose of a constructor is to prepare a new object for use.
  2. A constructor differs from a method in that the constructor has ________ and ________. (answer)
  3. The name of the class that contains this code is ________. (why?)
    private Bug bug;
    private Flower flower;
    public BugWorld() {/* statements here */}
    
    1. Bug
    2. BugWorld
    3. Flower
    4. Cannot determine class name from the information given

4.1.3: The addObject() Method

  • The method header for the addObject() method is:
    void addObject(Actor object, int x, int y)
    
  • Where:
    • object: the new object to add
    • x: the x coordinate of the location where the object is added
    • y: the y coordinate of the location where the object is added
  • For example:
    addObject(new Bug(), 150, 100);
  • The method belongs to the World class and is inherited by our World subclass (BugWorld)
  • Since it is inherited, we can just call the method directly from a World subclass

Check Yourself

  1. True or false: use the addObject() method to add objects to a scenario world.
  2. When calling the addObject() method, you specify the object location using the ________ and ________ coordinates of the scenario world.
  3. True or false: you can call addObject() from any World subclass.

4.1.4: Creating New Objects

  • The addObject() method lets us add an object to the world
  • However, we must first have an object to add
  • The Java keyword new lets us create new objects
  • For instance:
    new Bug()
  • We can create the object within the addObject() method call:
    addObject(new Bug(), 150, 100);
    
  • Another way is to save the object in a variable and use the variable in the method call:
    Bug myBug = new Bug();
    addObject(myBug, 150, 100);
    
  • Notice that the data type of the variable is the name of the class: Bug
  • Since the first technique is more compact, it is most often used
  • We only use the second technique if we want to use the object later in the code
  • We will discuss this technique later in the course
  • The key point is that you must use the new keyword to create a new object

Check yourself

  1. True or false: the purpose of the addObject() method is to add objects to a scenario world.
  2. For a class named Foo, you create a new object using the code ________.
    1. new Foo
    2. Foo()
    3. new() Foo
    4. new Foo()
  3. To place a Bug object in the world at the coordinates (200, 300) use the statement ________.
    1. addObject(new Bug(), 200, 300);
    2. addBug(200, 300);
    3. addActor(new Bug(), 200, 300);
    4. addObject(Bug.class, 200, 300);

Exercise 4.1

In this exercise, we automatically initialize our Bug scenario.

Specifications

  1. Download the following scenario file and save it in the scenario folder of Greenfoot.

    Scenario file: bugs3.zip.

  2. Start Greenfoot and open the scenario by choosing Scenario > Open and then selecting the zip file.

    Greenfoot unzips the file for us.

  3. Open the source code editor of the Bug class by double-clicking on Bug in the inheritance hierarchy, or by right-clicking on the Bug class and selecting Open editor.
  4. In the prepare() method, add code like the following to add a bug to the scenario.
    addObject(new Bug(), 150, 100);
    

    Compile the class and verify there are no errors. Resolve any errors you find, getting help from a classmate or the instructor as needed.

  5. Create several Flower objects and add them to the scenario as well.

    For more information see lesson: 4.1.4: Creating New Objects.

  6. Compile and run your scenario to verify all the changes work well.

    If you have problems, ask a classmate or the instructor for help as needed.

  7. In addition, add one or more lizards to your scenario.

    Compile the class and verify there are no errors. Resolve any errors you find, getting help from a classmate or the instructor as needed.

  8. Save a copy of your scenario to upload to Blackboard later as part of assignment 4.

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

As time permits, read the following sections and be prepared to answer the Check Yourself questions in the section: 4.1.5: Summary.

4.1.5: Summary

  • Games and simulations need to place actors automatically
  • To automatically place an actor, you use the constructor of the World subclass (like BugWorld)
  • The purpose of a constructor is to prepare a new object for use
  • A constructor is coded like a method but with two important changes:
    • No return type
    • Same name as the class name
  • Greenfoot sets up an optional prepare() method for initialization
  • You can either use the prepare() method or place the initialization code directly in the constructor
  • To add an actor to a scenario, you use the addObject() method
  • For example:
    addObject(new Bug(), 150, 100);
  • Notice that we create a new object programmatically in the addObject() method
    new Bug()
  • The other two parameters are the (x, y) coordinates for the actor

Check Yourself

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

  1. True or false: scenarios should always have actors placed manually. (4.1.1)
  2. What is the purpose of a constructor? (4.1.2)
  3. Which of the following is NOT a difference between a method and a constructor? (4.1.2)
    1. A constructor name is always the same as the class name whereas a method name need not be the same.
    2. A constructor cannot not return a value but a method can return a value.
    3. A constructor is called automatically when the object is created whereas a method must be called explicitly.
    4. All of these other answers are differences between a method and a constructor.
  4. Which of the following is a difference between a method and a constructor? (4.1.2)
    1. The name is the same as the class name.
    2. The name is the same as the class name, except lower case.
    3. The name cannot start with a number.
    4. The name cannot have spaces.
  5. Which of the following is a difference between a method and a constructor? (4.1.2)
    1. A constructor cannot have parameters.
    2. A method has a name but a constructor does not.
    3. A method body is enclosed in curly braces but a constructor body is enclosed in parenthesis.
    4. A method always has a return type, unlike a constructor.
  6. True or false: the addObject() method has three parameters. (4.1.3)
  7. For a class named Foo, which of the following is a valid expression for creating a new object? (4.1.4)
    1. new Foo
    2. Foo()
    3. new() Foo
    4. new Foo()

4.2: Animating Images

Learner Outcomes

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

  • Discuss animation using images
  • Write programs with animated images
  • Write code for instance variables
  • Assign values to instance variables

4.2.1: About Image Animation

  • Animation is the illusion of motion created by displaying a series of images or shapes
  • For example, the following animation displays at 10 frames per second (FPS):

    example animation

  • The speed of the display is fast enough that you cannot easily see the individual frames
  • Contrast this with the following image that displays at 2 frames per second:

    example animation at slower frame rate

  • At 2 FPS, the animation is slow enough that you can see the individual frames
  • Both of these animations were produced by displaying these images, known as frames:

    animation frames

  • Note that these images are in the public domain and were obtained from Wikipedia

Check Yourself

  1. Animation is the ________ of motion created by displaying a series of images or shapes.
  2. True or false: if the animation is too fast, it appears jerky.
  3. Each image in an animation is sometimes called a ________.

4.2.2: Adding Images to a Scenario

  • We want to apply image animation to make our actors look more realistic
  • For this, we need to add more images to our bug scenario
  • The following are two similar but slightly different images we can use for our bug
  • The slight difference is in the position of the legs

Images for Animation

Bug with legs forward Bug with legs sideways Bug with legs back
Bug with legs forward Bug with legs sideways Bug with legs back

Saving Images in a Scenario

  • We can save these images in our scenario
  • Right click the images and select, "Save Image As..." (or "Save Picture As..." in IE)
  • In the Save Image dialog, find the Greenfoot scenario folder for your project and save in the images folder
  • In Greenfoot, right click on the actor and select, "Set image..."

    Set image menu

  • You will see the images on the left in the Scenario images area
  • Click the image to select it and press the OK button

Select image dialog

Check Yourself

  1. True or false: to create an animation we sometimes want to change the images of an actor.
  2. The name of the command for adding images to a scenario is ________.
  3. True or false: you cannot import new images into a Greenfoot scenario.

4.2.3: Greenfoot Images

  • Greenfoot has a class named GreenfootImage that helps us use an image
  • We can get an image by creating a new GreenfootImage object:
    new GreenfootImage("bug-a.gif");
    
  • All actors have images and get one from their class by default
  • However, we can change the images in an actor object by calling a method
  • There are two methods in the Actor class that lets us change an image
    void setImage(String filename)
    void setImage(GreenfootImage image)
    
  • Where:
    • filename: the name of an image file
    • image: a GreenfootImage object
  • We could use the first method and load the image directly
  • However, it is better to use the second method for animation
  • The reason is that we want to change the image many times every second
  • Loading an image from a file is a relatively slow operation
  • However, if we load both images only once and we can simple exchange
  • To make this trick work, we need to save an image once we load it from a file
  • To save the images, we need to discuss instance variables

Check yourself

  1. To change the image of an Actor call the method ________.
  2. True or false: in Greenfoot, the name of the class for storing images is called GreenfootImage.
  3. Of the following, ________ is NOT one of the methods of Actor that works with images.
    1. getImage()
    2. setImage(String)
    3. setImage(GreenfootImage)
    4. changeImage(GreenfootImage)

4.2.4: Instance Variables (Fields)

  • An instance variable, also called a field, is like the local variable we discussed in lesson 2.3.2
  • General syntax:
    private dataType VariableName1, VariableName2, ...;
    
  • Where:
    • dataType: one of the Java data types
    • VariableNameX: the name of the variable
  • For example:
    private int count;
    private GreenfootImage image1;
    
  • Technically, we can use words other than private, but for now always use private
  • Can you identify each of the syntax items in the examples above?

Comparing Local Variables and Instance Variables

  • Like a local variable, an instance variable is a place in memory to store information
  • Also, like a local variable we specify a data type and a name to declare a variable
  • Likewise, the naming rules of local and instance variables are the same
  • In addition, you assign values to both local and instance variables using an equals ("=") sign
  • In contrast, a local variable is declared inside a method while an instance variable is declared outside of any method
  • This is because the memory for an instance variable is associated with an object rather than a method
  • Also, the instance variable has an accessibility modifier: private

Example of Three Instance Variables Declared in a Class

import greenfoot.*;

// comments omitted

public class Bug extends Mover
{
    private GreenfootImage image1, image2, image3;

    // methods omitted
}

Check yourself

  1. True or false: an instance variable is a place to store date in memory.
  2. True or false: A local variable is declared inside a method while an instance variable is declared outside a method, though still inside a class.
  3. The three parts of this instance variable are known as a(n):
    private GreenfootImage image1;
    1. private: ________
    2. GreenfootImage: ________
    3. image1: ________

4.2.5: Writing Actor Constructors

  • In section 4.1.2, we discussed how to use the constructor of the world class to initialize the world
  • In a similar way we can use a constructor in an actor class to initialize the actor
  • The world class had a constructor included automatically by Greenfoot, but an actor does not
  • Instead we write our own constructor using the following syntax
    public ClassName(parameterList) {
        statements
    }
    
  • Where:
    • ClassName: the same name as the class
    • parameterList: the types and names of the parameters
    • statements: the commands to execute when the method is called
  • Technically, we can use words other than public, but for now always use public
  • You can see an example of a constructor in an actor class below

Example of a Constructor in an Actor Subclass

import greenfoot.*;

// comments omitted

public class Bug extends Mover
{
    private GreenfootImage image1, image2, image3;

    public Bug()
    {
        image1 = new GreenfootImage("bug-a.gif");
        image2 = new GreenfootImage("bug-b.gif");
        image3 = new GreenfootImage("bug-c.gif");
        setImage(image1);
    }

    // methods omitted
}

Constructing Objects

  • Notice how we create multiple new GreenfootImage objects and save the images for later use
  • The purpose of a constructor is to set up an object including instance variables
  • After the constructor finishes, we have four objects:
    • Three GreenfootImage objects
    • One Bug object
  • The instance variables are part of the Bug object and allow us to refer to the GreenfootImage objects
  • This is shown in the following diagram
  • The first object (Bug) is constructed in the world constructor
    addObject(new Bug(), 150, 100);
  • The image objects are constructed in the actor constructor
    image1 = new GreenfootImage("bug-a.gif");
    image2 = new GreenfootImage("bug-b.gif");
    image3 = new GreenfootImage("bug-c.gif");
    
  • These variables are known as reference variables because they refer to an object
  • We can see the reference variable in the following image

Bug Object With Variables Pointing to Image Objects

Bug object with instance variables

Check yourself

  1. The purpose of an Actor constructor is to ________
  2. True or false: an instance variable is a variable defined in a class for which each object (instance) has a separate copy.
  3. True or false: a reference variable is a variable for a class type.
  4. Of the following variable declarations, ________ is a reference variable.
    1. int x;
    2. double trouble;
    3. float away;
    4. String aling;

4.2.6: Alternating Images with if/else Statements

  • Now that we have multiple images available, it is time to do the animation
  • For the animation to work, we need to alternate between them
  • In other words, whenever we are were showing image1 we now want to show image2
  • Also, whenever we are were showing image2 we now want to show image1
  • This is somewhat hard to explain using natural language alone
  • It often helps to write out ideas like this using psuedocode

Psuedocode

  • Psuedocode is an informal description of the steps for solving a problem
  • We just want to express the idea and do not try to write programming code
  • For instance:
    if (current image is image1) then
        display image2 now
    else if (current image is image2) then
        display image3 now
    else
        display image1 now
    
  • Notice that our pseudo code is a mixture of natural language and programming code

Implementing the Alternation With if/else Statements

  • When choosing between alternatives, we use an if/else-if statement
  • Syntax:
    if (test1)
    {
       statements1
    }
    else if (test2)
    {
       statements2
    }
    else
    {
       statements3
    }
    
  • Where:
    • testX: the test conditions to evaluate
    • statementsX: the statements to execute depending on the test
  • For example:
    if (getImage() == image1)
    {
        setImage(image2);
    }
    else if (getImage() == image2
    {
        setImage(image3);
    }
    else
    {
        setImage(image1);
    }
    
  • The first test condition that evaluates to true is selected and no others
  • Notice that there is no test condition for the else clause
  • The else clause serves as the default condition

Check yourself

  1. True or false: psuedocode is a good technique for working out the logic of a program.
  2. If the current image displayed is image1, the image displayed after the following code fragment runs is ________.
    if (getImage() == image1)
    {
        setImage(image2);
    }
    else
    {
        setImage(image1);
    }
    
  3. True or false: there is a separate test condition for both the if and the else clause of an if/else statement.

Exercise 4.2

In this exercise, we add animation to our bugs scenario.

Specifications

  1. Start Greenfoot and open the Bug scenario from the last exercise.
  2. Add the following images to the Bug scenario, saving the images with the names shown below the image:
    Bug with legs forward Bug with legs sideways Bug with legs back
    bug-a.gif bug-b.gif bug-c.gif

    For more information see lesson: 4.2.2: Adding Images to a Scenario.

  3. Add three instance variables to the Bug class named image1, image2 and image3 that are suitable for storing GreenfootImage objects.

    For more information see lesson: 4.2.4: Instance Variables (Fields).

  4. Add a constructor to the Bug class and assign the following values to the instance variables image1 and image2:
    image1 = new GreenfootImage("bug-a.gif");
    image2 = new GreenfootImage("bug-b.gif");
    image3 = new GreenfootImage("bug-c.gif");
    

    For more information see lesson: 4.2.5: Writing Actor Constructors.

  5. Write a method named updateImage() that alternates between the images, and then call that method from the act() method.

    For more information see lesson: 4.2.6: Alternating Images with if/else Statements.

  6. Compile and run your scenario to verify all the changes work well.

    If you have problems, ask a classmate or the instructor for help as needed.

  7. Save a copy of your scenario to upload to Blackboard as part of assignment 4.

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

As time permits, read the following sections and be prepared to answer the Check Yourself questions in the section: 4.2.7: Summary.

Programming Challenge

The current scenario does not allow the bug to stop moving. Change the scenario so that the bug moves forward only when the up-arrow key is pressed.

4.2.7: Summary

  • Animation is the illusion of motion created by displaying a series of images or shapes:

    example animation

  • We looked at how to apply image animation to make our actors look more realistic
  • For this we discussed how to add more images to our scenarios
  • Then we discussed the GreenfootImage class and how to construct new image objects
    new GreenfootImage("bug-a.gif");
  • You can change the image displayed by calling the setImage() method
  • To create an animation, we need to change the image many times per second
  • The best way to change the images repeatedly is to load the images once and save them in a GreenfootImage object
  • We looked at how to save images in an object and then refer to them with instance variables
  • An instance variable is like a local variable but becomes part of the object
  • While instance variables are declared in a class, each object has its own set instance variables
  • To initialize the instance variable, we added a constructor to an actor (see below)
  • After executing the constructor, you end up with multiple objects like this:

    Bug object with instance variables

  • To develop our thinking on alternating objects, we used pseudo code:
    if (the current image is image1) then
        display image2 now
    else
        display image1 now
    
  • Psuedocode is an informal description of the steps for solving a problem
  • We then translated the pseudo code to program code using an if/else statement

Code Snippet With Instance Variables and Constructor

import greenfoot.*;

// comments omitted

public class Bug extends Mover
{
    private GreenfootImage image1, image2, image3;

    public Bug()
    {
        image1 = new GreenfootImage("bug-a.gif");
        image2 = new GreenfootImage("bug-b.gif");
        image3 = new GreenfootImage("bug-c.gif");
        setImage(image1);
    }

    // methods omitted
}

Check Yourself

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

  1. What is animation? (4.2.1)
  2. What is the name of the method for adding images to a scenario? (4.2.2)
  3. True or false: in Greenfoot, the name of the class for storing images is called GreenfootImage. (4.2.3)
  4. Which of the following is NOT one of the methods of Actor that works with images? (4.2.3)
    1. getImage()
    2. setImage(String)
    3. setImage(GreenfootImage)
    4. changeImage(GreenfootImage)
  5. True or false: an instance variable is a place to store date in memory. (4.2.4)
  6. What is the difference between a local variable and an instance variable? (4.2.4)
  7. True or false: an instance variable is a variable defined in a class for which each object (instance) has a separate copy. (4.2.5)
  8. What is the purpose of a constructor? (4.2.5)
  9. If the current image displayed is image1, what image is displayed after the following code fragment runs? (4.2.6)
    if (getImage() == image1)
    {
        setImage(image2);
    }
    else
    {
        setImage(image1);
    }
    
  10. True or false: there is a separate test condition for both the if and the else clause of an if/else statement. (4.2.6)

4.3: Counting and Arithmetic

Learner Outcomes

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

  • Count in Java
  • Discuss the two ways that Java stores numbers
  • Code simple arithmetic

4.3.1: Counting Flowers

  • Games need a way to win and a way to loose and scenarios must end
  • We already have a way to loose our scenario -- the bug gets eaten by a lizard!
  • However, we still need a way to win the scenario
  • One way we can win our scenario is to count the number of flowers eaten
  • When our bug eats some number of flowers, say 8, we win the game
  • We can also play a short success sound when this happens

Counting

  • To keep track of the number of flowers eaten, we need to count
  • In Java, counting is done with a variable, a little arithmetic and an assignment statement
  • We start by declaring a variable like:
    private int flowersEaten;
  • As we discussed in lesson 4.2.4, we always start an instance variable with the word private
  • The data type int means we are storing integer (whole number) data
  • As we learned before, we assign new values to variables using a single equal (=) sign
    flowersEaten = 0;
  • Remember that the equal sign is really an assignment operator and does not denote equality
  • Thus, unlike math, you can have the same variable on both sides of an equals sign:
    flowersEaten = 0;     // initialize count to 0
    flowersEaten = flowersEaten + 1; // add to count
    
  • Note that the value of the variable is changed in the second line
  • In an assignment statement, the right-hand side is always evaluated first
  • Thus we read the value of flowersEaten from memory and add 1 to it
  • Then we assign the value back to the flowersEaten variable as the concluding step
  • As a result, the variable is incremented by 1

    Incrementing a variable by 1

Check yourself

  1. True or false: the following variable is an instance variable.
    private int count;
  2. The value of count after the following code executes is ________.
    int count = 0;
    count = count + 1;
    
  3. In the following assignment statement, the ________ side of the equals sign is evaluated first.
    count = count + 1;

4.3.2: Winning the Game

  • Now that we can count, let us look at how to win the game
  • In the lookForFlower() method, we increment our flowersEaten variable
    flowersEaten = flowersEaten + 1;
  • After we increment the variable, we test to see if we have met the win condition
  • If so, we play the success sound and stop the game
  • Here is a success sound we can use: success.wav
  • You can see the updated lookForFlower() method below

Method lookForFlower() With Win Condition

/**
 * Checks whether we have stumbled upon a flower.
 * If we have, then eat it. Otherwise, do nothing.
 */
public void lookForFlower()
{
    if (canSee(Flower.class)) {
        eat(Flower.class);
        Greenfoot.playSound("slurp.wav");

        flowersEaten = flowersEaten + 1;
        if (flowersEaten >= 8) {
            Greenfoot.playSound("success.wav");
            Greenfoot.stop();
        }
    }
}

Testing Our Code

  • You should always test your code after any change to make sure it works correctly
  • In general, you should test your code every time you make a change
  • To test our counting code, we can inspect our Bug object

    Inspectint the bug

  • When the scenario runs, notice how the flowersEaten variable increments each time the bug eats a flower

Check Yourself

  1. True or false: when an object contains an instance variable, we can see the value of the instance variable by inspecting the object.
  2. The three statements for counting flowers are:
    1. ________
    2. ________
    3. ________

4.3.3: More About Numbers

  • While we are working with numbers, lets discuss how Java handles them
  • Java has two general types of numbers: integers and floating-point (decimal)
  • An integer is zero or any positive or negative number without a decimal point
  • For example:
    0   1   -1    +5    -27   1000    -128
  • We call numbers like these literal integers because they represent what they look like
  • Java stores the integer types as a binary number
  • A floating-point number is any signed or unsigned number with a decimal point
  • For example:
    0.0   1.0   -1.1   +5.   -6.3    3234.56    0.33
  • Note that 0.0, 1.0 and +5. are floating-point numbers, but could be rewritten as integers
  • Floating point numbers are stored in a standard format known as IEEE 754
  • As you can see, integers and floating-point numbers are stored in different ways
  • Because of the differences, you must specify the data type of a variable so Java can handle them numbers correctly
  • In Java, both integers and floating-point numbers cannot have any commas or special symbols

Check yourself

  1. The two types of numbers in Java are ________ and ________.
  2. Of the following literal numbers, ________ is an integer.
    1. 1
    2. 1.2
    3. 1.23
    4. 1.234
  3. If you want to count with whole numbers, use a(n) ________ data type.

More Information

4.3.4: Arithmetic

  • When you work with numbers, you often want to perform some simple arithmetic
  • Java uses the following operators for arithmetic:
    • + for addition
    • - for subtraction
    • * for multiplication
    • / for division
    • % for modulus (remainder after division)
  • As in algebra, multiplication and division are performed before addition and subtraction
  • To change the order of operation, you use parentheses
  • For example:

    a + b / 2 is written as: a + b / 2

    (a + b) / 2 is written as: (a + b) / 2

Notes About Arithmetic

  1. You can use parentheses to group expressions
    • Anything within the parentheses is evaluated first
      2 * (10 + 5)
  2. You can have parentheses within parentheses
    • Innermost parenthesis evaluated first
      (2 * (10 + 5))
  3. Parentheses cannot be used to indicate multiplication
    • Invalid expression: (2)(3)
    • Must use the * operator

Programming Style

  • Programming style: add spaces around binary operators
    • 2 + 3, not 2+3
  • Programming style: no spacing after opening or before closing parenthesis
    • (2 / 3), not ( 2/3 )

Check yourself

  1. The five arithmetic operators in Java are ________.
    1. +, -, /, *, %
    2. +, -, \, *, %
    3. +, -, /, *, ^
    4. +, -, \, *, ^
  2. The first operation performed in the following arithmetic expression is ________.
    1 + 2 * 3 / 4 % 5
    
  3. If we wanted a different ordering of operations in the above example, we add ________ to the expression.

Exercise 4.3

In this exercise, we add a successful ending condition (win!) to our scenario.

Specifications

  1. Start Greenfoot and open the Bug scenario from the last exercise.
  2. Add an instance variable to the Bug class named flowersEaten that is suitable for storing integer numbers.

    For more information see lesson: 4.3.1: Counting Flowers.

  3. In the constructor of the Bug class, set the value of flowersEaten to zero (0).
  4. In the lookForFlower() method, add code to increment the value of flowersEaten.

    For more information see lesson: 4.3.1: Counting Flowers.

  5. Save the following sound file in the scenario sounds directory: success.wav

    For more information see lesson: 3.4.4: Adding Sound.

  6. In the lookForFlower() method, add code to test the number of flowers eaten and play both the success.wav sound and stop the game.

    For more information see lesson: 4.3.2: Winning the Game.

  7. Save a copy of your completed lesson scenario to upload to Blackboard as part of assignment 4.
  8. Complete the crossword puzzle shown below and be prepared to share your answers.

Crossword Puzzle

Fill in the crossword which is based on concepts from this section.

  1
              2
 
3
       
            4
   
               
      5
       
6
               
                   

Across

3. Base two number system
6. Used to group arithmetic expressions

Down

1. What it looks like
2. ______-point; number with a decimal point
4. Number of arithmetic operators (as a word)
5. Data type for an integer

As time permits, read the following sections and be prepared to answer the Check Yourself questions in the section: 4.3.5: Summary.

4.3.5: Summary

  • Games need a way to win and a way to loose and scenarios must end
  • In this section we looked at how to win our scenario by counting the number of flowers our bug ate
  • To keep track of the number of flowers eaten, we need to count
  • In Java, counting is done with a variable, a little arithmetic and an assignment statement
  • The pattern is to declare and initialize a variable by setting its value to zero (0)
  • Every time we want to add to the count, we add one to the variable
  • For example:
    flowersEaten = 0;     // initialize count to 0
    flowersEaten = flowersEaten + 1; // add to count
    
  • To check for a winning condition, we just add an if-statement like:
    if (flowersEaten >= 8) {
        Greenfoot.playSound("success.wav");
        Greenfoot.stop();
    }
    
  • We also looked at how we can test the code by inspecting the Bug:

    Inspectint the bug

  • In general, you should test your code every time you make a change
  • We also looked at numbers and arithmetic in this section
  • Java has two general types of numbers: integers and floating-point
  • Integers are whole numbers (no decimal point) and floating point numbers have decimal points
  • Both types of numbers are stored in a different way by the computer
  • Because of the differences, you must specify the data type of a variable so Java can handle them numbers correctly
  • Java uses the following operators for arithmetic:
    • + for addition
    • - for subtraction
    • * for multiplication
    • / for division
    • % for modulus (remainder after division)
  • As in algebra, multiplication and division are performed before addition and subtraction
  • To change the order of operation, you use parenthesis

Check Yourself

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

  1. What is the value of count after the following code executes? (4.3.1)
    int count = 0;
    count = count + 1;
    
  2. True or false: You should always test your code after making changes. (4.3.2)
  3. How can you tell the difference between an integer and a floating-point number? (4.3.3)
  4. Which of the following is an integer? (4.3.3)
    1. 1
    2. 1.2
    3. 1.23
    4. 1.234
  5. What are the five operators Java provides for arithmetic? (4.3.4)
  6. What is the first operation performed in the expression: 1 + 2 * 3 / 4 % 5? (4.3.4)

4.4: Sharing Scenarios

Learner Outcomes

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

  • Share your scenarios with others
  • Publish scenarios on the web

4.4.1: Exporting Your Scenarios

  • When you have finished a scenario, you may want to share it with others
  • Users of your work need to start and run the scenario, but not to see the class diagram or source code
  • Greenfoot has the capability to export a scenario so that others can use, but not change, your scenario
  • Also, you can decide whether to share your source code or not

Exporting Scenarios

  • To export scenarios, you click the Share button
  • After this, you will have a choice of three export options:

    Scenario export types

  • Application produces an executable file that will run on any computer with Java installed
  • Webpage produces a webpage and applet that you can place on the web if you have access to a web server
  • Publish adds your scenario to the Greenfoot Gallery on the web at greenfootgallery.org
  • We will look at each of these options in the following sections

4.4.2: Exporting to an Application

  • The most straightforward approach is to export as an application
  • An application is a program that users can run on any computer with Java installed
  • Java application files have a .jar suffix, which is short for Java ARchive
  • To distribute your scenario, you just give people a copy of your executable JAR file
  • All you need to specify in the dialog is where you want to save the JAR file
  • An option is to lock your scenario
  • Locking a scenario removes the Act button and the speed slider
  • Typically you lock the scenario for games
  • However, if you have a more experimental simulation, you can export your scenario without locking

Export to Application Dialog

Export to application dialog

4.4.3: Exporting to a Web Page

  • Another option is to export to a web page
  • This option creates a web page with your scenario showing as a Java applet
    • An applet is an application that runs inside another application
    • In this case, the applet runs inside a web browser
  • If you have access to a web server, you can publish this page to your web space
  • If you do not have access to a web server then choose one of the other options
  • To see an example of the web page as created for the bug scenario click here

Export to Webpage Dialog

Export to webpage dialog

4.4.4: Publishing on the Greenfoot Gallery

  • The last export option lets you publish your scenario to the web at greenfootgallery.org
  • The Greenfoot Gallery is a public site that anyone can use
  • However, to submit scenarios or post comments, you need to register
  • Registration is to make sure everyone follows the rules of:
    • Be nice
    • Don't do anything stupid, offensive or illegal
  • When you choose this option, you will see a dialog like that shown below
  • Before you can upload, you will need to create an account by following the link in the dialog
  • You can change or even delete any scenarios that you upload
  • Notice the "Cabrillo" tag
  • This lets us find other Cabrillo students

Export to Gallery Dialog

Export to gallery dialog

4.4.5: Summary

  • Greenfoot makes it easy to share your scenarios with others
  • You can create a simple executable JAR file that people can run on any computer with Java installed
  • Another option is to create a webpage that runs a Java applet
  • If you have your own web space, then this is a good option for sharing your scenario
  • If you do not have your own web space, then you can still publish on the web using the Greenfoot Gallery
  • The Greenfoot Gallery is a public web space that the makers of Greenfoot provide
  • Anyone can view and use the scenarios on the gallery
  • However, to submit scenarios or post comments, you need to register

More Information

Check Yourself

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

  1. What are three ways to share your scenarios? (4.4.1)
  2. True or false: exporting as an application creates a JAM file. (4.4.2)
  3. True or false: exporting as a web page produces a Java cotlet that displays on the page. (4.4.3)
  4. True or false: anyone can publish to the Greenfoot Gallery as long as you register. (4.4.4)

Exercise 4.4

In this exercise, we export our Bug scenario.

Specifications

  1. Start Greenfoot and open the Bug scenario from the last exercise.
  2. Click the Scenario menu and select Export...

    Scenario export menu

  3. Export the Bug scenario as an Application and save the file to a convenient location like the Desktop.

    For more information see lesson: 4.4.2: Exporting to an Application. There is no need to turn in the exported file.

As time permits, be prepared to answer the Check Yourself questions in the section: 4.4.5: Summary.

Wrap Up

Due Next:
A3: Methodical Improvement (2/29/12)
A4: Finishing Touches (3/7/12)
  • When class is over, please shut down your computer
  • You may complete unfinished lesson exercises at any time before the due date.
Home | Blackboard | Schedule | Syllabus | Room Policies
Help | FAQ's | HowTo's | Links
Last Updated: April 14 2012 @21:51:32