7. Abstraction and Arrays

What We Will Cover


Illuminations

NASA Swarmathon

  • Cabrillo Robotics Club participating
  • You can join the Robotics Club
  • Opportunity to improve your programming skills

Questions from last class or the textbook?

Homework Questions?

  • Lab 6: Piano Practice (3/7/17)
    Q6: Scenario Mashup (3/9/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
  • Notice that the next quest is a guild project

Learning from the Midterm

Learner Outcomes

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

  • Know what was missed on the midterm
  • Decide on what you need to do to improve your performance, if anything
  • Write code to respond to mouse clicks

7.1.1: Post Midterm Review

  • If you had problems with a topic I suggest reviewing the notes, homeworks and labs
  • If you believe a question was graded incorrectly, please email me an explanation
  • We will have another midterm boss event before the final
  • Grading policies are listed in the syllabus

7.1.2: Post Midterm Survey

7.1.3: Making the Grade

  • Oftentimes students who get less than an "A" on the midterm wonder if they can still get an "A" in the course
  • Since this is the first midterm, the answer is "Yes" unless:
    • You have not completed most of the homework
    • AND you failed the midterm with < 50%
  • Even with the above, you can still pass the course and even get a "B"
  • However, you will need to start doing more homework and study for the tests

Suggestions for Improving your XP

  • Start planning and studying for the next boss event (midterm) now
  • Take notes and rewrite them the day after a class meeting
  • Review your notes every week and identify possible exam problems
  • Analyze your homework and get help on items with which you have problems
  • Study with others by reviewing homework problems and practicing with possible exam questions
  • Use your instructors' office hours to ask questions about material you don't understand

Exercise 7.1: Midterm Self-Reflection

In this exercise we reflect on our progress in this course.

You Can Learn Anything: from the Khan Academy (1:30)

  • Brain research shows that we can grow our brain interconnections
  • Like a muscle, the more we work with our brain the more it grows
  • When things are easy our brain may grow a little
  • However, the most growth occurs when we struggle with things
  • Research shows that our brain grows the most when we get a question wrong
  • So if we did not do well on the midterm, we have an opportunity to grow our brain
  • When we review why we got something wrong, that is when our brain grows the most
  • If we keep reviewing why we got something wrong, we are on our way to a more capable brain

Specifications (3m)

  1. Please take out a piece of paper and something to write with.

    There is no need to tear the paper out of a notebook. If you need paper or a writing tool, ask a classmate or the instructor for one.

  2. Reflect on the following questions and write down an answer for yourself:
    1. Are you achieving your goals for this course?
    2. What ways can you think of to improve your progress towards goals?
    3. What actions are you going to take to better meet your goals?

More Information

7.2: Reviewing the Piano Scenario

Learner Outcomes

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

  • Identify Java keywords
  • Write code for boolean variables
  • Use logical operators to combine multiple boolean expressions
  • Discuss the concept of abstraction as it applies to computer science
  • Write code to respond to mouse clicks

7.2.1: Testing Key Presses

  • In this lesson we review the new concepts from the Piano scenario
  • Lets download and unzip the completed Piano scenario:

    Scenario file: piano-complete.gfar.

  • Double-click the project.greenfoot file in the unzipped folder to start Greenfoot and open the scenario.

Examining the act() Method

  • Open the editor for the Key class and look at the source code
  • Notice the act() method, which is responsible for responding to key presses:
    private boolean isDown;
    
    public void act()
    {
        if (!isDown && Greenfoot.isKeyDown(key)) {
            play();
            setImage(downImage);
            isDown = true;
        }
        if (isDown && !Greenfoot.isKeyDown(key)) {
            setImage(upImage);
            isDown = false;
        }
    }
    
  • The book introduces two new concepts here: Boolean variables and logical operators
  • We looked at logical operators in lesson 5.2.2: Logical Operators
  • Remember that && means AND and ! means NOT
  • The && operator returns true if both operands are true and returns false otherwise
  • The ! operator negates the meaning of a logical expression

Boolean Variables

  • In the act() method we need the program to remember if the key is down or up
  • Another way to consider this: is the key down or not down?
  • To store a condition that can be only true or false, we use a Boolean variable
  • Boolean variables are named after George Boole (1815-1864), a pioneer in the study of logic
  • We specify a Boolean variable using the boolean data type, which can hold just one of two values: true or false
    boolean isCool = true;
    boolean isLies = false;
    
  • Question: What type of tests does George Boole give? (answer)
  • Question: How does George Boole order lunch? (see here)

    We can accomplish a lot with Boolean values.

Test Conditions and Boolean Values

  • Boolean variables are often used to save a current condition or state
  • For example, in this scenario we want to remember if a key was recently pressed
    • Pianos only play a sound once each time a key is pressed
  • To simulate this behavior, each Key class has a boolean variable:
    private boolean isDown;
    
  • Whenever the key is pressed, we assign this variable a value of true:
    isDown = true;
    
  • When the key is no longer pressed, meaning it was released, we assign the variable a value of false:
    isDown = false;
    
  • By tracking when the key is first pressed, we play a sound and change the image:
    if (!isDown && Greenfoot.isKeyDown(key)) {
        play(); // play a note
        setImage(downImage);
        isDown = true; // remember we played the note
    }
    
  • When the key is released, we just change the image:
    if (isDown && !Greenfoot.isKeyDown(key)) {
        setImage(upImage);
        isDown = false;
    }
    
  • The Boolean variable is needed to ensure a key press makes a sound only one time

Check Yourself

  1. True or false: the number of values that can be stored in a Boolean data type are 3: true, false and maybe.
  2. True or false: a test condition always evaluates to a Boolean value.
  3. True or false: the Boolean data type is spelled bool in Java.

7.2.2: Logical Operators

  • In the act() method we need to test two conditions at once:
    public void act()
    {
        if (!isDown && Greenfoot.isKeyDown(key)) {
            play();
            setImage(downImage);
            isDown = true;
        }
        if (isDown && !Greenfoot.isKeyDown(key)) {
            setImage(upImage);
            isDown = false;
        }
    }
    
  • A logical operator, also called a Boolean operator, is an operator that combines two test conditions into a single Boolean value
  • For example, the first test condition is:
    if (!isDown && Greenfoot.isKeyDown(key))
  • The two operands in the first test condition are:
    • !isDown (the ! means NOT in Java)
    • Greenfoot.isKeyDown(key)
  • We read this in English as:

    If NOT isDown AND Greenfoot.isKeyDown(key)

  • The entire test condition is true if the key was NOT down previously AND is down now
    • If the key was previously down then we skip the test condition
    • Also, if the key is currently up then we skip the test condition
  • Only when the conditions on both sides of the && are true is the entire test condition true
  • We discussed the truth tables for AND, OR and NOT in lesson 5.2.2
  • As a summary, the logical operators AND, OR and NOT are shown in the following table

  • Lets fill out the truth table for this piano Key class

Activity: Deciding When to Press and Release Keys (3m)

  1. For the following code, fill in the Action column of the table below as either Play, Release or leave blank for no change.
    if (!isDown && Greenfoot.isKeyDown(key)) {
        // Play note
    }
    if (isDown && !Greenfoot.isKeyDown(key)) {
        // Release key
    }
    
    isDown Greenfoot.isKeyDown(key) Combination (AND)
    F F
    T F
    F T
    T T
  2. Have your deskmate verify your answers.
  3. Press the Record button to submit your work.

Check Your Understanding

  1. For the following code and assuming the key is pressed, the test condition evaluates to ________.
    isDown = true;
    (!isDown && Greenfoot.isKeyDown(key))
    
  2. For the following code and assuming the key is released, the test condition evaluates to ________.
    isDown = true;
    (isDown && !Greenfoot.isKeyDown(key))
    
  3. For the following logical expressions, to test if x is between 1 and 10 (including 1 and 10) use ________.
    1. (x >= 1 && x <= 10)
    2. (1 <= x and x <= 10)
    3. (x >= 1 || x <= 10)
    4. (1 <= x or x <= 10)

7.2.3: Abstraction

  • Another concept covered in the scenario is abstraction
  • Abstraction is the reduction of a concept or idea to the most simple or essential characteristics
  • With abstraction, we filter out data that is not necessary to solve a certain type of problem
  • We use abstractions all the time, although we may not call them abstractions
  • Words, ideas, concepts, maps, models and symbols are all examples of abstractions
  • We could not think or speak without abstractions

Examples of Abstraction

  • Maps are abstractions

    Treasure map

  • A floor plan is an abstraction

    Hills-DeCaro House First Floor Plan Post-Fire

  • Ideas and concepts are abstractions

Abstractions in the Piano Scenario

  • The scenario uses abstraction to reduce the amount of code for the piano's keys
  • Rather than having separate code for 20 different piano keys, the scenario uses one set of code for all 20 keys
  • From the single Key class we then construct 20 key objects
  • Each key object plays different sounds, responds to different key presses and looks different when pressed or not pressed
  • By having one code source we reduce the amount of code and the chances for error in the code

Classes and Objects

One class can make many objects

Check Yourself

  1. Complete the following definition: An abstraction is a ________ representation that stands for some collection of individual instances.
    1. general
    2. specific
    3. fixed
    4. artistic
  2. True or false: One of the main characteristics of an abstraction is that it simplifies a complex phenomenon by leaving out the irrelevant details.
  3. When we simplify a set of real objects, like a soccer ball, to basic shared characteristics, like a Ball class, we are using a process known as ________.
    1. abstraction
    2. an abstract class
    3. summarization
    4. deep thought
  4. True or false: a single class can have many objects.

7.2.4: Generalizing with Parameters

  • After abstraction, we often represent an idea or a process in general terms so that we can use it to solve other problems that are similar
  • For example, in mathematics we write generalized formulas in terms of variables instead of numbers so that we can use the same formula with many different numbers like:

    f(x) = 2x + 3

  • With the above formula, we can plug in a value for x and get a final value
  • We use the same idea in programming when we add parameters to methods and constructors
  • For the piano, we generalize the Key class by adding parameters to the constructor

Constructors with Parameters

  • So far, all of the constructors we have written have had no parameters
  • If we were to write a constructor for the Key class with no parameters, it might look like this:
    private boolean isDown;
    private String key;
    private String sound;
    private String upImage;
    private String downImage;
    
    public Key()
    {
        key = "A";
        sound = "3c.wav";
        upImage = "white-key.png";
        downImage = "white-key-down.png";
        setImage(upImage);
        isDown = false;
    }
    
  • Constructors with no parameters are called default constructors because it sets instance variables to default values
  • To call the constructor, we create an object with the new operator, like:
    Key k = new Key();
  • To make a class more generally useful, we add constructors with parameters to the class

Example: Constructor with one Parameter

  • If we want to accept only some arguments, we code a constructor with the necessary parameters:
    // other instance variables omitted
    private String key;
    
    public Key(String newKey)
    {
        key = newKey;
        sound = "3c.wav";
        upImage = "white-key.png";
        downImage = "white-key-down.png";
        setImage(upImage);
        isDown = false;
    }
    
  • With the above constructor we construct an object with code like:
    Key k = new Key("A");
  • The argument we send to the parameter specifies which keyboard key to press to make the sound

Example: Constructor with Multiple Parameters

  • If we want to accept arguments for more instance variables, we code a constructor with parameters for each variable
  • Here is a Key constructor with four parameters:
    private boolean isDown;
    private String key;
    private String sound;
    private String upImage;
    private String downImage;
    
    public Key(String keyName, String soundFile, String img1, String img2)
    {
        sound = soundFile;
        key = keyName;
        upImage = img1;
        downImage = img2;
        setImage(upImage);
        isDown = false;
    }
    
  • These parameters let us construct a Key object with different keys, sounds and images
  • For example:

    Key a = new Key("A", "3c.wav", "white-key.png", "white-key-down.png");
    Key w = new Key("W", "3c#.wav", "black-key.png", "black-key-down.png");
    // more like this

Try It: Constructors with Parameters (4m)

  1. Download the following scenario file, save it to a convenient location like the Desktop and unzip the file.

    Scenario file: piano-complete.gfar.

  2. Double-click the project.greenfoot file in the unzipped folder to start Greenfoot and open the scenario.
  3. Open the editor for the Key class and add the following default constructor:
    public Key()
    {
        key = "A";
        sound = "3c.wav";
        upImage = "white-key.png";
        downImage = "white-key-down.png";
        setImage(upImage);
        isDown = false;
    }
    
  4. Test the default constructor by right-clicking the Key class in the inheritance diagram, and selecting new Key().
  5. In addition, add the following single parameter constructor:
    public Key(String newKey)
    {
        key = newKey;
        sound = "3c.wav";
        upImage = "white-key.png";
        downImage = "white-key-down.png";
        setImage(upImage);
        isDown = false;
    }
    
  6. Test the single parameter constructor by right-clicking the Key class in the inheritance diagram, and selecting new Key(String). Enter the name of a keyboard key in double quotes, like: "A".
  7. 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.

  8. Save your updated scenario as we will be adding to it in the next exercise.
  9. Be prepared to answer the following Check Yourself questions when called upon.

Check Yourself

  1. True or false: we can use a parameter to customize how a constructor or method operates.
  2. A constructor with no parameters that may assign default values to member variables is known as a ________ constructor.
  3. Given the following class code
    private int hours, minutes;
    Clock(int h, int m)
    {
        hours = h;
        minutes = m;
    }
    
    and after calling the code like this:
    Clock clk = new Clock(12,34);
    The value of instance variable hours is ________ and minutes is ________.

7.2.5: Local Variables, Parameters and Shadowing

  • When we write a constructor with parameters, we must be careful to make the parameter name different than the instance variable name
  • Otherwise, we have a problem known as shadowing
  • For example, if we define the following constructor in the Key class
    private String key;
    public Key(String key) {
        key = key;
        // other code omitted
    }
    
  • and then we call the above constructor by constructing an object
    Key k = new Key("A")
    The value of the instance variable key is the empty string("") instead of "A"
  • The reason is that when a local variable, like the parameter key above, has the same name as an instance variable, the compiler assumes we are referring to the local variable
  • One way to make if clear to the compiler that we are referring to an instance variable is to use the keyword this, as in:
    private String key;
    public Key(String key) {
        this.key = key;
    }
    
  • Another way to clarify the variable reference is by using a different parameter name, like:
    private String key;
    public Key(String keyName) {
        key = keyName;
    }
    
  • If we are not careful, then who knows that problems we may encounter? Only the Shadow knows

Check Yourself

  1. When a parameter has the same name as an instance variable, this is known as ________.
  2. Given the following class code
    private int hours, minutes;
    Clock(int h, int m)
    {
        hours = h;
        minutes = m;
    }
    
    and after calling the code like this:
    Clock clk = new Clock(12,34);
    The value of instance variable hours is ________ and minutes is ________.
  3. Given the following class code
    private int hours, minutes;
    Clock(int hours, int minutes)
    {
        hours = hours;
        minutes = minutes;
    }
    
    and after calling the code like this:
    Clock clk = new Clock(12,34);
    The value of instance variable hours is ________ and minutes is ________. (Why?)

7.2.6: Detecting Mouse Presses in the Key Class

  • One of the problems with the Piano scenario is that the user cannot press a key with a mouse
  • We can add this feature quite easily using the Greenfoot method:
    static boolean mousePressed(Object obj)
    
  • The method is static which means we can call it using the name of the class followed by the method name
    Greenfoot.mousePressed(this)
    
  • Since the return type is boolean, the method returns true or false and we can use it in an if-statement
  • Also, notice that the parameter type is Object
  • This means it can accept any Java object or the keyword null
  • Usually the object will be an Actor or World
  • If we call the method from an the act() method of an Actor then usually the parameter will be this
    if (Greenfoot.mousePressed(this)) {
        play();
        setImage(downImage);
    }
    
  • The keyword this is a special value that means this current object

Releasing the Key

  • The above code keeps the key down when clicked by a mouse
  • We need to add another if-statement to test for when the mouse press is released
  • The Greenfoot method that lets us know when a mouse pressed event is over is named mouseClicked()
  • Thus we can write:
    if (Greenfoot.mouseClicked(null)) {
        setImage(upImage);
    }
    
  • The keyword null tells the method to return true when any mouse click has completed

Greenfoot Mouse Methods

Method Description
getMouseInfo() Returns a MouseInfo object that can be queried about the state of the mouse
mouseClicked(Object obj) Returns true if the mouse has been clicked (pressed and released) on the given object.
mouseDragEnded(Object obj) Returns true if the mouse has been dragged and then the button released.
mouseDragged(Object obj) Returns true if the mouse has been dragged starting on the given object.
mouseMoved(Object obj) Returns true if the mouse has been moved on the given object.
mousePressed(Object obj) Returns true if the mouse button has been pressed over the given object.

Try It: Adding Mouse Clicks (4m)

  1. Start Greenfoot and open the Piano scenario from the last Try It.

    If you did not keep the scenario, then download piano-complete.gfar, save it to a convenient location like the Desktop and launch the scenario.

  2. Open the editor for the Key class and find the act() method.
  3. Add the following code to the act() method to play the key when the mouse button is pressed.
    if (Greenfoot.mousePressed(this)) {
        play();
        setImage(downImage);
    }
    
  4. Compile and run the scenario to test your code. What do you see when clicking on piano keys?
  5. Now add the following code to the act() method to show a different image when a mouse button is released.
    if (Greenfoot.mouseClicked(null)) {
        setImage(upImage);
    }
    
  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 as we will be adding to it in the next exercise.
  8. Be prepared to answer the following Check Yourself questions when called upon.

Check Yourself

  1. True or false: we can call a static method using the class name rather than an object.
  2. The special value for objects that means "no object" is the keyword ________ .
  3. The keyword ________ means this current object.
  4. To check if a mouse key has been pressed over a particular Actor object, call the Greenfoot method ________.

More Information

7.2.7: Tracing Code

  • One critical programming skill is tracing program code, often statement by statement
  • In a sense, we have to "be the computer"

    Be the computer

  • To trace the code, we follow the order that the statements execute
  • The order that the statements execute is known as the flow of execution

Tracing the Flow of Control

  • Remember from lesson 2.2.4 that Greenfoot executes by continuously calling the act() method of every class
  • All the act() methods of every class are called to update the scenario before Greenfoot draws (renders) the images
  • After rendering the images, Greenfoot pauses a short time
  • This sequence of events is known as an animation loop

    update,render,sleep

  • To trace the flow, we start with the act() method of one of our classes
  • The flow moves from one line to the next unless we reach a flow-control statement (like an if-statement) or a method call
  • A method call transfers the flow to the first statement of the called method
  • When the method returns, the flow transfers back to the point from which the call was made
  • Thus, every time the flow of control reaches a method call, the program:
    1. Temporarily stops executing in the current method
    2. Jumps to the called method and executes the statements of that method
    3. Returns to the point in the code from which it jumped
  • If the method returns a value (non-void methods), then the returned value is substituted for the method call
  • Let us trace the flow in the following code by line number

Example Code for Tracing the Flow

We trace the example code starting with the "A" key being pressed and assuming:

boolean isDown = false;

Tracing Example

  • The above code is from the Key class
  • As we trace, we record our progress by line number
  • For our example, we trace the code when a key is first pressed
  • The act() method starts executing on line 56
  • The test condition of the if-statement is evaluated first
  • When a key is first pressed, isDown has a value of false
  • The (!isDown) on the left side of the && evaluates to true
  • The right side of the && is a method call to Greenfoot.isKeyDown--
  • We look up the method in the Greenfoot API and see it returns true if the key is pressed
  • A (true && true) condition evaluates to true, so we execute the statements inside braces
  • Line 59 is a method call to play(), so we:
    1. Temporarily stop executing the act() method
    2. Jump to the play() method and execute the statements of that method
    3. Return to the point in the code from which we jumped
  • After returning, we move on to the next line which is a call to setImage()
  • Method setImage() is part of the Greenfoot API, so we note that it sets the image and continue to the next line
  • On line 61, we set the value of isDown to true
  • On line 63, the test condition of the if-statement evaluates to false
  • Thus, we skip the statements inside the braces and reach the end of the act() method
  • We also check the test conditions on lines 67 and 71
  • The sequence of line numbers was: 56, 58, 59, 60, 61, 63, 67, 71
  • Notice that we did not bother to list blank lines or lines containing only the curly braces { or }
  • We can follow this same process when a key is released

Check Yourself

  1. True or false: when tracing the flow of execution, we often keep track of our position by using line numbers.
  2. While running, Greenfoot calls the ________ method continuously so we start tracing inside this method.
  3. When the flow reaches a method call, it
    1. Temporarily ________ executing the current method
    2. ________ to the called method and executes its statements
    3. When finished executing, ________ to the point from which the flow jumped
  4. True or false: when the flow calls an API method, we can look up the method to see what it does but do not track the line numbers of the API method.
  5. A program that helps debug other programs is called a(n) ________.

7.2.8: Introducing the Greenfoot Debugger

  • A debugger is a program used to test and debug other programs
  • Greenfoot has a debugger which is easily accessed from the editor window
  • The debugger helps us trace the order of statements executed (flow)

Starting the Greenfoot Debugger

  • We start debugging by first pausing the program if it is running
  • Then we choose where we want the debugger to stop the program by clicking in the left-hand margin of the editor window
  • When we click a small stop sign appears in the left margin
    Stop sign
  • The stop sign is the breakpoint where the debugger will stop your program
  • As an example, place a stop sign on the first call to play() in the act() method
  • Press the Run button and then press the "A" key on the keyboard
  • Notice how the program stops and the following debugger window appears

Greenfoot Debugger Window

Greenfoot debugger window

  • The debugger window shows us the current state of our class
  • The Call Sequence window shows which methods have been called
  • To the right of the Call Sequence are three windows showing the state of our variables
  • Java has three types of variables:
    • Static variables
    • Instance variables
    • Local variables
  • Each type appears in their own window
  • At the bottom are five buttons as follows:
    • Halt: called automatically
    • Step: move to the next line, but not into method calls
    • Step into: move to the next line and into method calls
    • Continue: resume the program
    • Terminate: stop and restart the program
  • By pressing the Step or Step into buttons repeatedly, we can follow the flow of our code

Check Yourself

  1. A program that helps debug other programs is called a(n) ________.
  2. The Step button moves to the next line but not ________.
    1. into method calls
    2. into Greenfoot code
    3. beyond the current method
    4. between classes
  3. To move to the next line, including into method calls, we press the button named ________.
    1. Step
    2. Step into
    3. Continue
    4. Terminate

Exercise 7.2: Tracing the Flow (5m)

In this exercise, we trace the program flow of the Key class.

Specifications

  1. Start Greenfoot and open the Piano scenario from the last Try It.

    If you did not keep the scenario, then download piano-complete.gfar, save it to a convenient location like the Desktop and launch the scenario.

  2. Open the editor for the Key class and find the act() method.
  3. Make sure you have completed the Try It for Adding Mouse Clicks. Your act() method should look like the following though line numbers may vary.

Key class act() method

  1. Compile and run your scenario to verify it works correctly, playing sounds with key presses and mouse clicks.

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

  2. Prepare a text file named trace.txt to record the flow of the Key class act() method.
  3. Using the Greenfoot debugger, trace the flow of the code in the Key class act() method by listing the line numbers that are executed when the "A" keyboard key is pressed. Record the line numbers in trace.txt.

    For more information see lesson: 7.2.7: Tracing Code.

  4. In addition, trace the flow of the code by listing the lines number that are executed when a mouse button is pressed. Record the line numbers in trace.txt.

    If you have difficulty, ask a guild member or the instructor for help as needed.

  5. Save your trace.txt file to submit as part of Lab 6 in the "lessons" folder. In addition, save your Piano scenario for the following exercises.

As time permits, please help those around you.

7.2.9: Review

  • A logical operator, or Boolean operator, is an operator that connects two Boolean test conditions
  • We use logical operators to combine multiple Boolean expressions into one Boolean result
  • We looked at examples from the key class:
    if (!isDown && Greenfoot.isKeyDown(key))
  • As a summary, the logical operators AND, OR and NOT are shown in the following table

  • Another concept covered in the scenario is abstraction
  • Abstraction is the reduction of a concept or idea to the most simple or essential characteristics
  • The scenario used abstraction to reduce the amount of code for the piano's keys
  • Rather than having separate code for 20 different piano keys, the scenario uses one set of code for all 20 keys
  • After abstraction, we often represent an idea or a process in general terms so that we can use it to solve other problems that are similar
  • For the piano, we generalize the Key class by adding parameters to the constructor
  • The book used a constructor with the following signature:
    public Key(String keyName, String soundFile, String img1, String img2)
    
  • These parameters let us construct a Key object with different keys, sounds and images like:
    Key a = new Key("A", "3c.wav", "white-key.png", "white-key-down.png");
    Key w = new Key("W", "3c#.wav", "black-key.png", "black-key-down.png");
    // more like this
    
  • When we write a constructor with parameters, we must be careful to make the parameter name different than the instance variable name
  • We also looked at how to detect mouse clicks using:
    Greenfoot.mousePressed(this)
    
  • In addition, we looked at tracing code by following the steps the computer is taking
  • We learned how to use the Greenfoot debugger to stop the program and step though our code line by line

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

  1. Words with predefined meanings in a programming language are called ___________. (7.2.1)
  2. List five keywords found in the Key class:
  3. True or false: A boolean variable can store only the values true, false or null. (7.2.2)
  4. True or false: a test condition always evaluates to a boolean value. (7.2.2)
  5. Given the following variable declarations, what is the value of the following Boolean expressions? (7.2.3)
    int a = 1;
    int b = 2;
    int c = 3;
    int d = 4;
    
    1. (a == c || a == b): _____
    2. (a == c || a != b): _____
    3. (a == b && c == d): _____
    4. (a == b && b == c): _____
  6. True or false: If false is 0 and true is 1, then AND is the maximum of the inputs. (7.2.3)
  7. True or false: If false is 0 and true is 1, then OR is the maximum of the inputs. (7.2.3)
  8. ______________ is a programming technique to write code that can solve a whole class of problems, rather than a single specific problem. (7.2.4)
  9. True or false: After applying abstraction, the amount of code is usually smaller. (7.2.4)
  10. Which of the following is a method to detect if the mouse button has been pressed but not released? (7.2.6)
    1. mouseClicked(Object obj)
    2. mouseMoved(Object obj)
    3. mouseKeyPressed(Object obj)
    4. mousePressed(Object obj)
  11. The usual object to use with the above mouse method is a(n) _____________ subclass. (7.2.6)
  12. The special keyword that means the current object is ______. (7.2.6)

7.3: Using Loops and Arrays

Learner Outcomes

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

  • Describe two new ways to inspect data
  • Write counting loops
  • Use arrays to store predefined lists of data

7.3.1: Reviewing the Piano Class

  • Let us review the Piano class in Greenfoot for key concepts including:
    • Starting a class
    • Specifing a superclass
    • Signature of the constructor
    • Calling the superclass constructor
    • Calling methods from the constructor
    • Signature of a method
    • Declaring and initializing an array

Magic Numbers (Why 54?)

  • Notice the code for placing white keys:
    addObject(key, i * 63 + 54, 140);
    
  • Each of the numbers are important but what do they mean? Click to show answer
  • Numbers like these are called magic numbers
  • They are magic because their value is unexplained but necessary
    • Often, no one knows what they mean after 3 months, including the author
  • We can often deduce the meaning of numbers after reading the code carefully, which is time consuming
  • A much better coding style is to use named constants rather than literal numbers
  • We discussed constant variables in lesson 5.1.4
  • For example:
    private static final int KEY_HEIGHT = 280;
    private static final int KEY_WIDTH = 63;
    private static final int KEY_OFFSET = 54;
    // ...
    addObject(key, i * KEY_WIDTH + KEY_OFFSET, KEY_HEIGHT / 2);
    
  • Now it is much easier to understand the code and see any problems or limitations
  • Another reason to use named constants is that it is easier to make changes
  • We simply change the constant value rather than finding all the associated occurences of a number

Check Yourself

  1. To inspect the values of the instance variables of an object, right-click the object and select the word ________ from the menu.
  2. Write a statement that will print the variable "y" to the terminal window.

    answer

  3. If the x-coordinate of the first white piano key is 54 then the third white piano key is at the x-coordinate ________.

7.3.2: The while Loop

  • One important new concept introduced in the Piano scenario is the loop statement
  • By default, program code flows sequentially -- one statement after another
  • When we want to repeat a section of code we can use a loop statement
  • We first looked at for-loops in lesson 4.2.4 to randomly add objects
  • In lesson 5.1.5 we used the for-loop to place tiles in a scrolling game
  • Java has three general purpose loop statements
    • for
    • while
    • do...while
  • The simplest loop is the while statement

Syntax of a while-loop

  • A while statement has a test condition and a body, like an if statement
  • Before each execution of the loop body, the while statement checks the test condition
  • If the test condition evaluates to true, then our program executes the body of the loop
  • When the program reaches the end of the loop body, it automatically returns to the while statement
  • Syntax:
    while (test) {
       statement1
       statement2
       ...
    }
    
  • Where:
    • test: the test condition to evaluate
    • statementX: the statements to execute while the test remains true
  • Here is a while loop example from early in the Piano scenario:
    int i = 0;
    while (i < 12)
    {
        addObject(new Key("g", "3a.wav"), (i*63) + 54, 140);
        i = i + 1;
    }
    
  • Notice how the repeated code is indented inside the loop
  • This lets us see easily which code is repeated and which is not
  • Also, we can easily see which starting and closing braces match
  • The following flow chart shows how the while loop operates

Diagram of while Loop Operation

While loop flow chart

Counting with the while-loop

  • We can use a while-loop for counting just like a for-loop
  • Recall that a for-loop has the form
    for (i = start; i < end; i++) {
        ...
    }
    
  • Where:
    • i: the name of a counter variable
    • start: the initial starting count
    • end: the final ending count
  • We can provide the same function with a while-loop by adding extra statements:
    i = start;
    while (i < end) {
        ...
        i++;
    }
    
  • Normally we use a for-loop for counting
  • However, this comparison shows how the while-loop operates

Example Comparing a while-Loop and a for-Loop

int i = 0;
while (i < 12)
{
    addObject(new Key("g", "3a.wav"), (i*63) + 54, 140);
    i = i + 1;
}
for (int i = 0; i < 12; i = i + 1)
{
    addObject(new Key("g", "3a.wav"), (i*63) + 54, 140);
}

Try It: Writing a while Loop (3m)

  1. Start Greenfoot and open the Piano scenario from Exercise 7.2.

    If you did not keep the scenario, then download piano-complete.gfar, save it to a convenient location like the Desktop and launch the scenario.

  2. Open the editor for the Piano class and find the constructor method.
  3. Add the following while-loop code to the constructor method.
    System.out.println("while loop");
    int counter = 0;
    while (counter < 5)
    {
        System.out.println(counter);
        counter = counter + 1;
    }
    
  4. Compile and run the scenario to test your code. What do you see when you click the compile button?
  5. Be prepared to answer the following Check Yourself questions when called upon.

Check Yourself

  1. Clap your hands 10 times.
    1. You know when to stop because you ________
    2. Every time you clap, the ________ changes.
  2. For the example loop shown below, the loop repeats ________ times.
    int counter = 0; // initialization (starting value)
    while (counter < 5)  // test condition
    {
        System.out.println(counter);
        counter = counter + 1;  // update the count
    }
    
  3. True or false: the purpose of the variable counter is to keep track of the number of repetitions.
  4. True or false: if counter started at 100 (counter = 100), the loop body would never execute.
  5. True or false: if the statement updating the count was omitted, like in the code shown below, the loop would never stop repeating until the program was stopped.
    int counter = 0; // initialization (starting value)
    while (counter < 5)  // test condition
    {
        System.out.println(counter);
    }
    

7.3.3: Arrays

  • Another new concept introduced in the Piano class is the array

    Array: an ordered arrangement of identically-typed data values

  • An array is used to process a collection of data of the same type
  • The data stored in the array can be of any single type: int, String, and so on
  • One way to construct an array is like the first example in the Piano class:
    private String[] whiteKeys = { "a", "s", "d", "f", "g",
        "h", "j", "k", "l", ";", "'", "\\" };
    
  • In this example, the array variable's name is whiteKeys
  • The type of the variable is String[], which is pronounced, "String array"
  • The expression on the right hand side of the equals sign constructs an array object and fills it with values

    { "a", "s", "d", "f", "g", "h", "j", "k", "l", ";", "'", "\\" }

  • When the program executes the first statement, it creates 12 slots in memory like this:

    whiteKeys = 
    "a"
    "s"
    "d"
    "f"
    "g"
    "h"
    "j"
    "k"
    "l"
    ";"
    "'"
    "\\"
    [0]
    [1]
    [2]
    [3]
    [4]
    [5]
    [6]
    [7]
    [8]
    [9]
    [10]
    [11]

  • Each of the items inside an array slot is known as an element
  • The number inside of the square brackets is known as an index
  • Notice that the first index is 0 (zero)

Accessing an Element

  • Once we have the array in place, we can access the elements using the index
  • The index is the position number of the element
  • For example, the string "a" is at position 0, "s" at position 1, and so on
  • We use the index with the variable name of the array to access an element
  • As an example, we would access the "g" element as follows:
    whiteKeys[4]
  • Here is a summary of array terminology

    array

Try It: Creating an Array (2m)

  1. Start Greenfoot and open the Piano scenario from the last Try It.

    If you did not keep the scenario, then download piano-complete.gfar, save it to a convenient location like the Desktop and launch the scenario.

  2. Open the editor for the Piano class and find the constructor method.
  3. Add the following array and for-loop code to the constructor method.
    System.out.println("Array data");
    String[] data = { "A", "B", "C", "D", "E" };
    for (int i = 0; i < 5; i++)
    {
        System.out.println(data[i]);
    }
    
  4. Compile and run the scenario to test your code. What do you see when you click the compile button?
  5. Be prepared to answer the following Check Yourself questions when called upon.

Check Yourself

  1. The number inside of the square brackets of an array is called an ________ or subscript.
  2. The first element in any array has an index value of ________.
    1. -1
    2. 0
    3. 1
    4. 2
  3. Of the following, ________ will correctly access the fifth element of an array named "foo".
    1. foo[5]
    2. foo(5)
    3. foo[4]
    4. foo.array[4]
  4. If we have an array with 100 elements, the index number of the last element is ________.
  5. For the following array declaration, answer the questions below:

    private String[] words = { "Java", "and", "Greenfoot", "is", "totally", "cool", "and", "not sketch" };

    1. The value of words[0] is: ________
    2. The value of words[2] is: ________
    3. The value of words[5] is: ________
    4. The value of words[7] is: ________

7.3.4: Arrays and Loops

  • We can use a loop as a way to access each array element
  • Notice that the index of an array is an integer number
  • The index can be an integer variable, like those used in counter-controlled loops
  • Thus we can use arrays with the loop of our key-making code:
    private String[] whiteKeys = { "a", "s", "d", "f", "g",
        "h", "j", "k", "l", ";", "'", "\\" };
    private  String[] whiteNotes =
        { "3c", "3d", "3e", "3f", "3g", "3a", "3b", "4c",
        "4d", "4e", "4f", "4g" };
    
    // other code omitted
    
    for (int i = 0; i < whiteKeys.length; i = i + 1)
    {
        Key key = new Key(whiteKeys[i], whiteNotes[i] + ".wav",
            "white-key.png", "white-key-down.png");
        addObject(key, 54 + (i * 63), 140);
    }
    
  • The first time through the loop, when i = 0, the value of whiteKeys[i] is "a"
  • Also, the value of whiteNotes[i] is "3c" which is concatenated (joined) with ".wav" to produce "3c.wav"
  • Notice the plus sign "+" used to concatenate the two strings
  • Also notice the use of whiteKeys.length instead of 12
  • The expression arrayName.length returns the number of slots in the array

Check Yourself

For the second time through the loop:

  1. The value of the index variable i is ________
  2. The value of whiteKeys[i] is ________
  3. The value of whiteNotes[i] concatenated with ".wav" is ________

Exercise 7.3: Array and Loops (5m)

In this exercise, we work with loops and arrays in the Piano scenario.

Specifications

  1. Start Greenfoot and open the Piano scenario from the last Try It.

    If you did not keep the scenario, then download piano-complete.gfar, save it to a convenient location like the Desktop, unzip the file, and launch the scenario.

  2. Prepare a text file named loop.txt to record the data from the following steps.
  3. Locate the makeKeys() method and notice the two loops, one for the white keys and one for the black keys.
  4. Add a System.out.println() statement to both loops that prints the values of the arguments sent to the Key constructor with a vertical bar (|) separating each value.
    For example, add the following statement inside the white-key loop:
    System.out.println(whiteKeys[i] + "|" +  whiteNotes[i]+".wav" + "|" +  "white-key.png" + "|" +  "white-key-down.png");
    
  5. Copy the output from the terminal window to the loop.txt file.

    You may need to scroll or expand the terminal window to see all the values displayed.

  6. In addition, copy the following questions to the loop.txt file and then answer the questions.

    Q1: Why do the first two values on each line change, but not the last two values?

    Q2: What does the first value on each line represent?

    Q3: What does the second value on each line represent?

  7. Save your loop.txt file to submit as part of assignment 5 in the "lesson" folder.

As time permits, read the following review section and be prepared to answer the questions.

7.3.5: Summary

  • In this section we looked at loops and arrays
  • Loops execute a block of code repeatedly
  • The simplest loop is a while statement
  • Syntax:
    while (test) {
       statement1
       statement2
       ...
    }
    
  • A while statement which has a test condition and a body, like an if statement
  • Unlike an if-statement, a while loop automatically jumps back to the start after reaching the end of the code block
  • Before each execution of the loop body, the while statement checks the test condition
  • If the test condition evaluates to true, then the computer executes the body of the loop
  • One common use for loops is to count numbers
  • The for-loop gives us a compact way to program counter-controlled loops
    for (i = start; i < end; i++) {
        ...
    }
    
  • Here is a diagram showing the syntax and flow of the for-loop:

    for loop

  • An array is a list of data elements each identified by an index

    array

  • Arrays are used to keep a list of data that is easily accessed
  • Any type of data may be stored in an array, but all elements must be of the same type
  • Because the indices are integers, we often use counting loops to access array elements

Check Yourself

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

  1. Two more ways to inspect data are: (7.3.1)
    • Right-click an object and select __________
    • Use a _____________ statement
  2. Why is 54 the x-coordinate of the first piano key? (7.3.1)
  3. What is the purpose of a loop? (7.3.2)
  4. True or false: A while loop is like an if statement except the flow of the while loop returns to the test condition at the end of the loop body. (7.3.2)
  5. What part of a while loop is repeated? (7.3.2)
  6. A counting loop has the following three parts: (7.3.2)
    1. ___________________
    2. ___________________
    3. ___________________
  7. What is the value of counter after the following loop finishes executing? (7.3.2)
    int counter = 0;
    while (counter < 10) {
        // other code omitted
        counter = counter + 1;
    }
    
  8. An array is a way to make a _______ of data. (7.3.3)
  9. How many elements are present in the following array? (7.3.3)

    private String[] words = { "Java", "and", "Greenfoot", "is", "totally", "cool", "and", "not sketch" };

  10. What code do you write to access the fourth element of the above array? (7.3.4)
  11. Write a loop that accesses all the elements of the above words array. (7.3.4)

7.4: Making Bubbles

Learner Outcomes

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

  • Create colors, with and without transparency
  • Draw shapes on a GreenfootImage object

7.4.1: Imagery and Color

  • As part of the next quest we start working with colors and shapes
  • In this lesson we introduce how to work with colors and shapes
  • To help us, We will create a scenario for bubbles floating in space
  • However, instead of displaying bubbles from exisiting images, we will draw our own
  • The scenario is similar to the one in the textbook at the end of chapter 6

Creating Colors

  • Most video displays use a color model known as RGB (Red, Green, Blue)
  • The red, green and blue values combine to create the overall color:

    RGB colors

  • Greenfoot supports the standard RGB color model with the Color class
  • We create colors by specifying red, green and blue (RGB) values
  • RGB values are specified using int values from 0 to 255 for each read, green and blue component:
    Color(int r, int g, int b)  // 0 - 255
    
  • For example:
    Color chocolate = new Color(204, 102, 0);
    
  • To help choosing colors, the textbook on page 195 (1/e: 136) has a color chart of (r, g, b) values
  • In addition, the Color class has several static color constants that we can use in place of numbers as shown below
  • In Greenfoot, we make use of colors when we want to fill images or draw shapes
    image.setColor(Color.CYAN);
    image.fill();
    

Some Color Constants

Color Constant Red, Green, Blue
Color.RED 255, 0, 0
Color.BLUE 0, 0, 255
Color.YELLOW 255, 255, 0
Color.BLACK 0, 0, 0
Color.PINK 255, 175, 175
Color Constant Red, Green, Blue
Color.GREEN 0, 255, 0
Color.MAGENTA 255, 0, 255
Color.CYAN 0, 255, 255
Color.WHITE 255, 255, 255
Color.GRAY 128, 128, 128

Activity: Starting the Bubble Scenario (4m)

  1. Create a new scenario named "bubbles".

    Please use the specified names if you want XP credit because it makes grading easier.

  2. Create a World subclass with "No image" named BubbleWorld.
  3. Open the BubbleWorld editor and set the world size to 800 by 600 pixels.
  4. Set the background color of the world with code like the following, but choosing any color you prefer:
    GreenfootImage image = getBackground(); // gets the exisiting image
    image.setColor(Color.CYAN);
    image.fill();
    
  5. Save your scenario so you can update it in future exercises.

When finished please help those around you.

Check Yourself

  1. The three color components are: R__________, G__________, B__________.
  2. Write the code to construct the following colors in Java:
    Color red =   ; answer
    Color green = ; answer
    Color blue =  ; answer
    Color pink =  ; answer
    
  3. What are two ways to complete the following statement? (answer)
    Color magenta =
  4. Look at the Color Chart of RGB Triplets and fill in the code to construct the following colors:
    Color orange =
    Color purple =
    Color lime =
    

More Information

7.4.2: Pixel Transparency

  • Every pixel on a screen has two components: color and transparency
  • The transparency component of color is referred to as the alpha value
  • By adjusting the alpha value, background colors show through
  • We can see this effect in the following image
  • The color is less intense and the background checkerboard image becomes more visible as the alpha value decreases

    Effect of transparency

Setting the Transparency (Alpha) Value

  • We can work with the transparency of an image in two ways
  • One way is by using methods of GreenfootImage (see below)
  • Another way is to use the Color class directly
  • When constructing a Color object, we can specify a fourth value: alpha
    Color(int r, int g, int b, int a)  // 0 - 255
    
  • For example:
    Color myColor = new Color(146, 223, 227, 128);
    
  • Alpha values are specified using int values from 0 to 255
  • An alpha value of 0 is completely transparent (invisible) whereas 255 is completely opaque (solid)
  • Values in between 0 and 255 are translucent -- some background shows through

Some GreenfootImage Methods Used for Transparency Control

Method Description
getTransparency() Returns the current transparency setting.
setTransparency(int t) Set the transparency of the drawing color.

Check Yourself

  1. answer
  2. answer
  3. answer

More Information

7.4.3: Drawing Bubbles

  • To draw shapes like a bubble we generally create an Actor subclass like: Bubble
  • We will want a constructor for Bubble to create the bubble image
  • When we create a constructor it is useful to think of how we will use the constructor
  • For our Bubble class, we will want to set the size and color of a bubble
  • However, entering a color is time consuming so we will start with random colors
  • Thus we code a constructor with one parameters like:
    public Bubble(int size)
    {
        // create bubble image here
    }
    
  • Within the constructor of the Bubble class we construct a GreenfootImage object
  • GreenfootImage image = new GreenfootImage(size, size);
    
  • The first parameter of the GreenfootImage constructor is the width and the second is the height
  • We make the width and height the same for a round bubble

Creating a Random Color

  • For our constructor we create a random code from drawing a bubble
  • To creae a random color, we make a random number for each component of the color like:
    int red = Greenfoot.getRandomNumber(200) + 55;
    int green = Greenfoot.getRandomNumber(200) + 55;
    int blue = Greenfoot.getRandomNumber(200) + 55;
    
  • Because each component must be between 0 and 255, we make certain our numbers do not exceed 255
  • At the same time, we make sure of having at least some minimal amount of each color
  • For the alpha value we want the colors to be translucent like a bubble
  • At the same time we want the color to be opaque enough to be able to see the bubble
  • We arrive at a compromise for the alpha value like:
    int alpha = Greenfoot.getRandomNumber(140) + 40;
    
  • Once we have all the color components we set the drawing color:
    image.setColor(new Color(red, green, blue, alpha));
    

Drawing on the Image

  • Once the color is set we can draw shapes using one of the drawing methods of the GreenfootImage class
  • The method we are interested in is the fillOval() method:
    image.fillOval(0, 0, width - 1, height - 1);
    
  • The fillOval() method requires four arguments:
    x - the x coordinate of the upper left corner of the oval to be filled.
    y - the y coordinate of the upper left corner of the oval to be filled.
    width - the width of the oval to be filled.
    height - the height of the oval to be filled.
  • After drawing the image, we set it as the current image for our actor
    setImage(image);
    
  • Note that by default the background of a GreenfootImage is transparent
  • Thus all we will see is the shape we draw upon the image

Constructor for Class Bubble

/**
 * Construct a new bubble object.
 *
 * @param size  The size of the bubble.
 */
public Bubble(int size)
{
    GreenfootImage image = new GreenfootImage(size, size);

    // Random component for each color
    int red = Greenfoot.getRandomNumber(200) + 55;
    int green = Greenfoot.getRandomNumber(200) + 55;
    int blue = Greenfoot.getRandomNumber(200) + 55;
    // Translucency to simulate a bubble
    int alpha = Greenfoot.getRandomNumber(140) + 40;

    image.setColor(new Color(red, green, blue, alpha));
    image.fillOval(0, 0, size - 1, size - 1);
    setImage(image);
}

Adding Bubbles to the World

  • Once we can create Bubble objects, we add several to the world
  • Then we select the "Save the World" function
  • We can see our random colors change by pressing reset

Activity: Drawing Bubbles (5m)

  1. Start Greenfoot and open the bubbles scenario from the last activity.
  2. Make a subclass of Actor named Bubble

    For "Scenario images" choose "No image" as we will draw our own image.

  3. Open the editor for the Bubble class and add the following constructor to the Bubble class.
    /**
     * Construct a new bubble object.
     *
     * @param size  The size of the bubble.
     */
    public Bubble(int size)
    {
        GreenfootImage image = new GreenfootImage(size, size);
    
        // Random component for each color
        int red = Greenfoot.getRandomNumber(200) + 55;
        int green = Greenfoot.getRandomNumber(200) + 55;
        int blue = Greenfoot.getRandomNumber(200) + 55;
        // Translucency to simulate a bubble
        int alpha = Greenfoot.getRandomNumber(140) + 40;
    
        image.setColor(new Color(red, green, blue, alpha));
        image.fillOval(0, 0, size - 1, size - 1);
        setImage(image);
    }
    
  4. Compile your Bubble class to verify the code you added is correct.

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

  5. Test your Bubble class by adding several bubbles to the world and then right-clicking the world background and selecting the function "Save the World".
  6. Press the reset button a few times and observe the random colors generated for the bubbles.

    You may experiement with changing the colors to match your world background color.

  7. Save your updated scenario as we will be adding to it in the next Activity.

When finished please help those around you.

Check Yourself

  1. To construct an image with a size of width x height, write ________
  2. True or false: by default, a GreenfootImage has a transparent background.

7.4.4: Moving the Bubbles

  • We want to add movement to our bubbles so they float around the world
  • To allow a different speed for each bubble, we add an instance variable
    private int speed;
    
  • To our exisiting constructor we set the speed to a random amount between 1 and 3 pixels
    // Random speed: 1 to 3
    speed = Greenfoot.getRandomNumber(3) + 1;
    
  • Then in the act() method we add a move() command:
    move(speed);
    

Floating on the Wayward Breezes

  • When our bubbles move, they do not appear to float
  • We need to add some random turning to simulate floating
    if (Greenfoot.getRandomNumber(100) < 50) {
        turn(Greenfoot.getRandomNumber(7) - 3);   // -3 to 3
    }
    
  • In addition, our bubbles get stuck at the edge of the window
  • One easy option is to have the bubbles turn at the edge
    if (isAtEdge()) {
        turn(180);
    }
    
  • Another option is to move the bubble to the other side of the window

Method act() for Class Bubble

/**
 * Float in the world.
 */
public void act()
{
    if (isAtEdge()) {
        turn(180);
    }
    move(speed);
    if (Greenfoot.getRandomNumber(100) < 50) {
        turn(Greenfoot.getRandomNumber(7) - 3);   // -2 to 2
    }
}

Activity: Moving Bubbles (5m)

  1. Start Greenfoot and open the bubbles scenario from the last activity.
  2. Open the editor for the Bubble class and add an instance variable for the speed as follows:
    private int speed;
    
  3. Locate the act() method and add code to move a bubble like:
    move(speed);
    
  4. Also in the act() method, add code to turn at the edge, like:
    if (isAtEdge()) {
        turn(180);
    }
    
  5. In addition add random turning to simulate floating
    if (Greenfoot.getRandomNumber(100) < 50) {
        turn(Greenfoot.getRandomNumber(7) - 3);   // -3 to 3
    }
    
  6. Compile your Bubble class to verify the code you added is correct.

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

  7. Test your Bubble class and verify the bubbles "float" and change directions at the edge of the world
  8. Save your updated scenario as we will be adding to it in the next Exercise.

When finished please help those around you.

7.4.5: Multiple Constructors

  • Recall that we previously discussed constructors with parameters in section 7.2.4
  • Constructors may have parameters to allow each object to vary in some way
  • As an example, we added constructors with parameters to the Key class of our Piano scenario
  • In addition to parameters, we can have multiple constructors in each class
  • By having multiple constructors, we can create an object in different ways that are convenient for our program

Constructor Overloading

  • Having multiple constructors is known as constructor overloading
  • For each constructor we must have a different signature
  • A constructor signature consists of its name, its parameter types and the order of its parameters
  • For example, the signature of our current Bubble constructor is:
    Bubble(int)
    
  • Notice that parameter names are not part of a signature

Constructors for the Bubble Class

  • We will want to work with our Bubble class in different ways
  • For example, we may want random sizes and colors for our bubbles
  • Also, we may want to specify a size and color or even direction
  • To accomodate these different possibilities we create multiple constructors

Default Constructor

  • Let us start by adding a default constructor
  • A default constructor is helpful because we do not need to supply any arguments
  • We need both a size and color when we create a bubble
  • We can easily make a size with a random numbers, like:
    int size = Greenfoot.getRandomNumber(90) + 20;
    
  • We do not want our sizes too large or too small, so we allow a "good" range
  • We already have the code for a random color, but in another constructor
  • It would be nice if we were able to use the code from the other constructor
  • It turns out there is a way using constructor chaining

Chaining Constructors

  • Constructor chaining is where one constructor calls another constructor of the same class
  • To call another constructor, we use the keyword this() with parenthesis
  • Inside the parenthesis we supply an argument of the type needed for another constructor
  • Java matches the data type of the argument with the parameter type of the constructor to which we are chaining
  • When chaining, the call to this must be the first statement in the constructor
  • Thus we nest our size calculation inside the constructor call to this()

Default Constructor Chaining to Another Constructor

/**
 * Create a Bubble that floats, with random size and random color.
 */
public Bubble()
{
    // Create a random size, between 20 and 110 pixels
    this(Greenfoot.getRandomNumber(90) + 20);
}

Another Constructor with Chaining

  • Being able to assign an initial direction to a bubble would be useful
  • By using constructor chaining we can easily code this constructor variant

Example Constructor with Direction Parameter

/**
 * Create a Bubble that floats, with given size and initial float direction.
 */
public Bubble(int size, int direction)
{
    this(size);
    setRotation(direction);
}

Exercise 7.4: Finishing our Bubble Scenario (7m)

In this exercise, we finish our Bubble class.

Specifications

  1. Start Greenfoot and open the bubbles scenario from the previous Activities:
    1. Activity: Starting the Bubble Scenario
    2. Activity: Drawing Bubbles
    3. Activity: Movinging Bubbles
  2. Open the editor for the Bubbles class and add a default constructor:
    /**
     * Create a Bubble that floats, with random size and random color.
     */
    public Bubble()
    {
        // Create a random size, between 20 and 110 pixels
        this(Greenfoot.getRandomNumber(90) + 20);
    }
    
  3. Compile your Bubble class to verify the code you added is correct.

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

  4. Test your new constructor by right-clicking and adding one or more bubbles to the world using the default constructor.
  5. Add the following constructor that sets a size and direction
    /**
     * Create a Bubble that floats, with given size and initial float direction.
     */
    public Bubble(int size, int direction)
    {
        this(size);
        setRotation(direction);
    }
    
  6. Compile your Bubble class to verify the code you added is correct.

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

  7. Test your new constructor by right-clicking and adding one or more bubbles to the world using the new overloaded constructor with both a size and direction.
  8. Save a copy of your completed lesson scenario to add to on the next quest.

When finished please help those around you.

7.4.6: Review

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

  1. True or false: Most screens use a color model known as RYB (Red, Yellow, Blue). (7.4.1)
  2. Given the following code: (7.4.2)
    GreenfootImage image = new GreenfootImage(800, 340);
    image.setColor(new Color(255, 0, 255));
    
  3. True or false: Background colors show through more as the alpha value decreases. (7.4.3)
  4. True or false: A good way to draw shapes in a project is to use a subclass of Actor. (7.4.4)

7.5: Pair Programming

Learner Outcomes

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

  • Discuss the pros and cons of pair programming

7.5.1: Introducing Pair Programming

  • Pair programming is a style of programming in which two people work together on one computer at the same time:
    • Exactly two people: not one nor three or more
    • Exactly one computer: not two or more
  • One person enters the code and the other reviews each line of code as it is entered
  • The person using the mouse and keyboard is called the driver
  • The person reviewing is called the navigator
  • In addition to reviewing, the navigator:
    • Analyzes the design and code to prevent errors
    • Looks up reference materials like program syntax
  • Each person "drives" about half the time:
    • Physically get up and move positions when switching roles
  • At most 25% of our time is spent working alone:
    • Any work done alone is reviewed by the other person
  • The objective is to work together and to learn from each other
  • You cannot divide the work into two pieces with each partner working on a separate piece
  • If you are not both engaged in the process, you will not learn the material
  • More information: Pair Programming for Homework Assignments

Why Pair Program?

  • Students who pair program report:
    • Higher confidence in a program solution
    • More satisfaction with programming
  • Instructors report higher completion and passing rates

Video Explaining Pair Programming (10m)

Fun with Pair Programming: a professionally developed video (10 minutes)

Fun with Pair Programming Worksheet: follow along during the video

Check Yourself

  1. True or false: pair programming typically results in fewer errors and programs take less time to complete.
  2. The job of the driver is to ________ the code.
  3. The job of the navigator include ________ the code.
  4. You change who is driving when you pair-program to gain a different ________ on the problem.

More Information

7.5.2: Best Practices

  • You may choose any other student in this class for a partner
    • You may NOT program with a person from outside the class
  • Both of your names appear on the assignment
  • When choosing partners and working together, certain practices help you perform better
  • Pair-programmers are usually more successful when they have similar experience levels
  • However, pair programming can work with partners of different experience levels
    • The more experienced partner must be ready to mentor rather than just develop the program
  • Find a partner with whom you can easily exchange ideas
  • If you cannot work easily with someone, get another partner or work by yourself

The Rules of Pair Programming

Pair Programming Non-Performance (ref)

  • Silence immediately indicates a lack of collaboration
  • Disengagement when one member does not pay attention or does something else like email or texting
  • One member observes and offers little comment as they "watch the master"

More Information

Check Yourself

  1. True or false: there are no rules in pair programming.
  2. Indicators of pair programming poor performance include ________.
    1. one member is not paying attention
    2. one member observes and offers little comment as they "watch the master"
    3. silence
    4. all of these
  3. True or false: the rules of pair-programming require you to use only one computer at a time to edit and compile code.

Exercise 7.5: Finding a Programming Partner (3m)

In this exercise we see who might be a compatible pair-programming partner for the next homework assignment.

Specifications

  1. Within your guild find someone with which to pair on Quest 6 keeping in mind schedules and programming experience.
  2. If you cannot find someone in your guild then find another student in the class.
  3. If you cannot find someone in the class then ask the instructor for assistance.

Wrap Up

Due Next:
Q6: Scenario Mashup (3/9/17)
Lab 7: Autumn Leaves (3/14/17)
Q7: Extending Bubbles (3/16/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: March 11 2017 @15:24:34