3. More Sophisticated Programming

What We Will Cover


Illuminations

Questions from last class or the reading?

Homework Questions?

  • A2: First Program (2/22/12)
  • Download your original programming project scenario from Blackboard and open it on your computer.
  • The instructor will briefly review each project and answer questions
  • Students can view each others projects as well

3.1: Creating New Methods

Learner Outcomes

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

  • Define methods with and without parameters

3.1.1: Writing Methods

  • In the previous sections we added new behavior to the Bug class, like:
    • Turning at the edge of the world
    • Occasional random turns
    • Eating flowers
  • Notice that the act() method is getting longer and longer as we add code
  • If we continue adding code as we have, the method will become really long and hard to understand
  • We can improve the situation by organizing the code into smaller pieces
  • The way to organize code within a class is to write new methods

About Methods

Method -- a named sequence of statements defined inside a class.

  • We have looked at methods before, such as the canSee() method:
    /**
     * Return true if we can see an object of class 'clss'
     * right where we are.
     * False if there is no such object here.
     */
    public boolean canSee(Class clss)
    {
        Actor actor = getOneObjectAtOffset(0, 0, clss);
        return actor != null;
    }
    

Method Syntax

  • The general syntax for defining a new method is:
    public returnType methodName(parameter1, ..., parametern) {
        statements
    }
    
  • Where:
    • returnType: the data type of the value returned
    • methodName: the name you make up for the method
    • parameterx: the input values, if any
    • statements: the statements to execute when calling the method
  • Can you identify each of these syntax items in the example above?

Check Yourself

  1. True or false: people write methods to organize code into small understandable pieces.
  2. A method is a ________ sequence of ________ defined inside a class.
  3. For the following code, match the syntax item with the code
    public boolean canSee(Class clss)
    {
        Actor actor = getOneObjectAtOffset(0, 0, clss);
        return actor != null;
    }
    
1. Braces a. { }
2. Return type b. canSee
3. Second statement c. ()
4. Method name d. Actor actor = getOneObjectAtOffset(0, 0, clss);
5. First statement e. return actor != null;
6. Parameter list f. boolean

3.1.2: Example of Writing a New Method

  • As an example of writing a new method, let us make a method out of our code to look for a flower
  • For example:
    /**
     * 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);
        }
    }
    
  • The overall code is known as a method definition
  • The code defines a new method
  • Let us look at each part of the new method

Comments

  • The first four lines are a comment
  • Comments are ... comments -- notes to people reading the code
  • The computer ignores comments entirely
  • We write comments to explain our code to human readers
  • Every method should have a comment block like the example

Method signature

  • The next line after the comment is the method signature:
    public void lookForFlower()
    
  • We can technically use words other than public, but for now always use public
  • The return type is the keyword: void
  • The word void is used when we want to return nothing from a method
  • Following the return type is the method name: lookForFlowers
  • Method names follow rules similar to variable names:
    • A sequence of letters, digits, underscores -- cannot contain spaces
    • Must start with a letter and not a number
    • Names are case sensitive
    • Cannot be a keyword
  • By convention, method names in Java always start with a lower case letter
  • If the name logically has multiple words, then use capital letters to mark the start of a new word
  • Following the method name is a set of parenthesis
  • Inside the parenthesis are the parameters, if any
  • How many parameters are there in this example?

Method Body

  • The last few lines -- the curly braces and anything between them -- is called the method body
  • The method body contains the list of statements executed when the method is invoked (called)

Check Yourself

  1. True or false: The compiler ignores method comments.
  2. True or false: method names are case sensitive.
  3. What is wrong with the following method name?
    public void 4flowers() { }
  4. What is wrong with the following method name?
    public void switch() { }

3.1.3: Calling Methods

  • When we define a method, the code does not immediately get executed
  • In fact, defining a method does not guarantee it is ever executed
  • To execute the code in a method, we must code a method call
  • We can call our example method from inside the act() method using the code:
    lookForFlower();
    
  • Notice that the method call has an empty parameter list
  • The number and order of parameters must match the parameters defined in the method
  • In this case, there are no parameters defined and so the method call has an empty parameter list

Organizing with Methods

  • Our method and method call does not change the execution of our program
  • Instead, defining short methods like this makes programs easier to understand
  • As we add more code to a class, methods tend to become longer and longer
  • Longer methods are harder to understand
  • By separating our code into a number of short methods, we make the code easier to read
  • For example, if we were to organize all the code of Bug into short methods, we might end up with an act() method like:
    public void act()
    {
        turnAtEdge();
        randomTurn();
        move();
        lookForFlower();
    }
    
  • Understanding the act() method is now easier because it is short
  • We can clearly see the logic and flow of our act() method

Check Yourself

  1. True or false: defining a method means it will be executed.
  2. True or false: method calls always have parenthesis, even when a method does not define any parameters.
  3. True or false: defining short methods makes it easier to understand the logic of a program.

Exercise 3.1

In this exercise, we write new methods for our scenario.

Specifications

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

    Scenario file: bugs2.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 and add the following method:
        /**
         * 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);
            }
        }
    

    For more information see lesson: 3.1.2: Example of Writing a New Method.

  4. Change the act() method of Bug to call this new method.

    For more information see lesson: 3.1.3: Calling Methods.

  5. Change the act() method as follows and then add the two new methods needed for your program to function.
        public void act()
        {
            turnAtEdge();
            randomTurn();
            move();
            lookForFlower();
        }
    

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

  6. Organize the code in the Lizard class in a similar way.

    However, instead of looking for and eating flowers, look for and eat bugs.

  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 a copy of your scenario to upload to Blackboard later as part of assignment 3.

    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: 3.1.4: Summary.

3.1.4: Summary

  • As we add more code to methods, they can become too long to easily understand
  • The solution is to break up the long sequences of code into shorter sections using methods
  • Methods allow you to organize code within a class
  • To define a method, we use the following syntax:
    public returnType methodName(parameter1, ..., parametern) {
        statements
    }
    
  • Where:
    • returnType: the data type of the value returned
    • methodName: the name you make up for the function
    • parameterx: the input values, if any
    • statements: the statements to execute when the function is called
  • If the method does not return a value, we use the return type: void
  • Otherwise, we specify the type of data we want to return
  • A method name follows the same rules as variable names
  • However, the method name is always followed by a set of parenthesis
  • Inside the parenthesis are the parameters, if any
  • You should always provide a comment block before a method
  • The comment helps explain the method to humans reading the code
  • When we define a method, the code does not immediately get executed
  • To make use of the new method, you use a function call like:
    lookForFlower();

Check Yourself

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

  1. Why do programmers write methods? (3.1.1)
  2. What is a method? (3.1.1)
  3. How can you tell the difference between a method name and a variable name? (3.1.1)
  4. What are three items always present in a method signature? (3.1.1)
  5. What is the purpose of comments? (3.1.2)
  6. True or false: The compiler ignores comments. (3.1.2)
  7. What is wrong with the following method name? (3.1.2)
    public void 4flowers() { }
  8. What is wrong with the following method name? (3.1.2)
    public void switch() { }
  9. Which of the following is a method definition and which is a method call? (3.1.3)
    1. public void lookForFlower() { }
    2. lookForFlower();
  10. True or false: Within reason, shorter methods are easier to understand than longer methods. (3.1.3)
  11. How can you use methods to make your code easier to understand? (3.1.3)

3.2: Bells and Whistles

Learner Outcomes

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

  • Write code for keyboard interaction
  • Describe the String data type
  • Write code to produce sound effects
  • Write code to end a scenario
  • Find class and method documentation in the Greenfoot API

3.2.1: Keyboard Interaction and Strings

  • So far the actors in our scenario move on their own
  • What we want to do with our bug is get the player involved
  • We want the player to control the actions of the bug using the keyboard
  • The Greenfoot framework has a method that lets us check whether a key on the keyboard has been pressed
  • The method is in the Greenfoot class and its signature is:
    static boolean isKeyDown(String keyName)
    
  • As we can see, the method is static and the return type is boolean
  • This means that the method returns true or false and we can use it in an if-statement
  • However, notice that the data type of the parameter is new: String
  • In order to use this method, we need to look at the String data type

Strings

  • A string is a sequence of characters (letters, digits, other symbols)
  • To indicate a string in a program we enclose the characters within double quotes
  • For example:
    "This is a string"
    "b"
    "$3.95"
    "My name is Ed"
    
  • We can create variables for strings using the String data type
  • For example:
    String firstName;           // declaration
    firstName = "Edward";       // assignment
    String lastName = "Parrish" // declaration + assignment
    
  • When a method parameter expects a String, we must provide either characters in double quotes or a variable

Check Yourself

  1. To check whether a key on the keyboard has been pressed, call the Greenfoot class method ________.
  2. A(n) ________ is a sequence of character data.
  3. The name of the data type for storing strings in variables is ________.
    1. String
    2. string
    3. str
    4. Text

3.2.2: Using Strings to Specify Key Presses

  • To call the isKeyDown() method, we need a String argument
    static boolean isKeyDown(String keyName)
    
  • So what string do we provide for the method call?

Key Names

  • Every key on the keyboard has a name
  • For keys that produce a visible character, that character is their name
  • For example, the A-key is named "A" (or "a")
  • The number keys are: "0", "1", ..."9"
  • Other keys have names as well
  • The cursor keys are named: "up", "down", "left", "right"
  • Other control characters include: "enter", "space", "backspace"
  • The function keys are: "F1", "F2", .., "F12"
  • For more information, see the Class Greenfoot documentation

Using isKeyDown()

  • If we want to test for the right-cursor key, we write an if-statement like:
    if (Greenfoot.isKeyDown("right"))
    {
        // do something
    }
    
  • For example, to make an actor turn right by 10 degrees we would write:
    if (Greenfoot.isKeyDown("right")
    {
        turn(10);
    }
    
  • We can add this code to a method and call the method from the act() method
  • For instance:
    /**
      * Check if a control key has been pressed and react.
      */
    public void checkKeyPress() {
        if (Greenfoot.isKeyDown("right"))
        {
            turn(10);
        }
    }
    
  • Then the act() method would look like:
    public void act()
    {
        checkKeyPress();
        move();
    }
    

Check Yourself

  1. When calling isKeyDown() for the B-key, use the parameter ________.
  2. When calling isKeyDown() for the left-cursor key, use the parameter ________.
  3. Write the first line of an if-statement that tests when the left cursor key is pressed.

    answer

  4. The best place to put the above if-statement is in the ________ method.
    1. act()
    2. atWorldEdge()
    3. checkKeyPress()
    4. move()

3.2.3: Adding Sound

  • Another "bell and whistle" we can add to our scenario is sound
  • As before, a method in the Greenfoot class can help us
  • By looking through the documentation, we find the playSound() method
  • The method expects a String parameter, which is the name of the sound file
  • The scenario from the book has some sound files and we will use one for our example: slurp.wav
  • We must add the sound file to the "sounds" folder in our scenario
  • To play the sound, we use the command:
    Greenfoot.playSound("slurp.wav");
  • As you can see, the file name is specified as a string
  • A convenient place to add the command in the Bug class is in lookForFlower()

Getting Sounds

  • To play sampled sound, you will need some sound files
  • You can get free sound effects files from the Internet like:
  • You can search for sounds on the web using:
  • However, make sure you verify the licensing
  • Also you can create your own sounds using the microphone on your cell phone or other device
  • Then you can edit the sounds using a sound editing program
  • Some free sound editing programs you might try are:

Sound File Size

  • Sound files can become quite large
  • When developing a game, we need to find or develop sound files that convey the effect we want without becoming overly large
  • As a rule of thumb, we want no sound file larger than one megabyte
  • Also, the sum total of all sound files should be no larger than three megabytes
  • If we find our sound files are too large, we can use a sound editing program to reduce the size

Check Yourself

  1. To play sounds, first add the sound files to the ________ folder of your scenario.
  2. To play a sound file, call the Greenfoot class method ________.
  3. True or false: you can use any sound file you can find on the Internet.

3.2.4: Ending the Scenario

  • One last "bell and whistle" we can add to our scenario is to end execution when the bug is caught by a lizard
  • Again, the Greenfoot class has a method to help us
  • We just need to find the method
  • To find out what methods are available, we look in the Greenfoot API

The Greenfoot API

  • The documentation for the Greenfoot classes is known as the Greenfoot API
  • API is an acronym for Application Programming Interface
  • We can find the Greenfoot API in Greenfoot by using the Help menu

    From the Help menu, select Greenfoot Class Documentation

  • This will show us the documentation for all the Greenfoot classes in a Web browser
  • Another way to find the documentation is online at http://www.greenfoot.org/files/javadoc/
  • The API shows all the available classes and we can follow the hyperlinks to find details about each class

Finding the Method

  • The method we are interested in is in the Greenfoot class
  • We click on a hyperlink for the Greenfoot class
  • When we get to the class, scroll down and look through the methods
  • Each method is listed and the one we are interested in has an explanation that says

    Pause the execution.

  • You can follow the hyperlink of the method name and often get more detailed information about the method

Check Yourself

  1. The acronym API stand for A________ P________ I________.
  2. True or false: the name of the documentation for Greenfoot classes is called the Greenfoot API.
  3. To end a scenario, call the Greenfoot class method ________.

Exercise 3.2

In this exercise, we add keyboard controls and sounds to our scenario. In addition, we add a stopping condition.

Specifications

  1. Start Greenfoot and open the Bug scenario from the last exercise.
  2. Open the source code editor of the Bug class and remove the randomTurn() method call and method.
  3. In the Bug class, add code to turn right pressing the right-cursor key and left by pressing the left-cursor key.

    For more information see lesson: 3.2.2: Using Strings to Specify Key Presses.

  4. Compile the class and verify there are no errors. Then test your scenario to verify the bug changes direction under keyboard control.

    Resolve any errors you find, getting help from a classmate or the instructor as needed.

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

    For more information see lesson: 3.2.3: Adding Sound.

  6. In the source code of the Bug class and add the following code to the lookForFlower() method after the eat() method call:
    Greenfoot.playSound("slurp.wav");
    

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

  7. Compile the class and verify there are no errors. Then test your scenario to verify the lizard eats a bug when they meet.

    Resolve any errors you find, getting help from a classmate or the instructor as needed.

  8. Save the following sound file in the scenario sounds directory: au.wav

    For more information see lesson: 3.2.3: Adding Sound.

  9. Change the code in the Lizard class to play au.wav sound and the stop the scenario after eating the bug.

    For more information see lesson: 3.2.4: Ending the Scenario.

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

  11. Save a copy of your final scenario with all the changes made to upload to Blackboard as part of assignment 3.

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

3.2.5: Summary

  • In this section we looked at several features that add interest and excitement to a game or simulation
  • First we looked at how to control actors using the keyboard
  • The important method was found in the Greenfoot class:
    static boolean isKeyDown(String keyName)
    
  • The method checks to see if a particular key is pressed
  • The particular key is specified using a String parameter
  • A string is a sequence of characters and you can specify the characters by placing them in double quotes
  • For instance:
    "This is a string"
    "A"
    "left"
    "right"
    
  • Another way to send the parameter information is to use a String variable like:
    String leftKey;
    leftKey = "left";
    String rightKey = "right";
    
  • When a method parameter expects a String, we must provide either characters in double quotes or a variable
  • Every key on the keyboard has a name
  • For keys that produce a visible character, that character is their name
  • For example, the A-key is named "A" (or "a")
  • The number keys are: "0", "1", ..."9"
  • The cursor keys are named: "up", "down", "left", "right"
  • Other control characters are: "enter", "space", "tab", "escape", "backspace"
  • The function keys are: "F1", "F2", .., "F12"
  • Since the isKeyDown() method returns a boolean type, we can use it in an if-statement like:
  • If we want to test for the right-cursor key, we write an if-statement like:
    if (Greenfoot.isKeyDown("right"))
    {
        // do something
    }
    
  • Another "bell and whistle" we can make to our scenario is the addition of sound
  • We must first place the sound file in the sounds folder of our scenario
  • Then to play the sound, we use the command:
    Greenfoot.playSound("filename.wav");
  • Finally we discussed how to look up classes and method in the Greenfoot API
  • You can find the class documentation from within Greenfoot using the help menu
  • Selecting the Greenfoot Class Documentation from the Help menu opens the documentation in a browser
  • Once you have opened the document ion, you follow the hyperlinks to find the information you want

Check Yourself

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

  1. What method checks whether a key on the keyboard has been pressed? (3.2.1)
  2. What is a string? (3.2.1)
  3. The name of the data type for storing strings in variables is: (3.2.1)
    1. String
    2. string
    3. str
    4. Text
  4. What is the name of the B-key? (3.2.2)
  5. What is the name of the left-cursor key? (3.2.2)
  6. Where do you place sound files that you want to play in a scenario? (3.2.3)
  7. What is the name of the method that plays sounds? (3.2.3)
  8. True or false: the name of the documentation for Greenfoot classes is called the Greenfoot API. (3.2.4)
  9. What is the name of the method that ends a scenario? (3.2.4)

Wrap Up

Due Next:
A3: Methodical Improvement (2/29/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: May 25 2012 @19:47:09