CS2 Final exam Review notes - Glen Ridge Public Schools Final exam – Review notes 1 ... All...
Transcript of CS2 Final exam Review notes - Glen Ridge Public Schools Final exam – Review notes 1 ... All...
CS2
Final exam – Review notes
1
Unit 1
Java is an object-oriented language.
A Class in GreenFoot is a definition of “something” that you can create and manipulate
in your program.
Objects are created from a class.
You can think of the class as a blueprint and an object as a house made from the
blueprint, or the class as the cookie-cutter and the object as the cookie.
You can make many objects from one class.
All Greenfoot worlds have a World and Actor class when they are first created.
Things that an object can do are called methods. The Crab class below has one
method, act().
The Act method executes many times when the Run button is clicked.
The Crab class is an Animal and an Actor. It can also run the methods from Actor and
Animal.
The class hierarch below shows the relationship between the classes:
CS2
Final exam – Review notes
2
Below is an example of method definitions:
o public void move()
o public boolean canSee()
The word in front of the method name tells us if the method just does a task but does
not report a value or if it reports a value.
The word void means that the method does not report a value. It just performs a task
(similar to a command block in BYOB).
The word boolean means that the method reports a boolean value of true or false
(similar to a predicate block in BYOB).
The word int means that the method reports a whole number value (similar to a
reporter block which can return type other than Boolean).
This word in front of the method name is referred to as the return type of the method.
We can change how an Actor acts by changing the statements in the act() method. The
code for the Crab (above) makes the Crab move 1 pixel and turn 5 degrees.
move() and turn() are methods that the Crab class inherited from the Actor class.
The turn method requires an input value to do its job. An input to a method is called a
parameter.
The code in the CrabWorld class determines the size of the world display and the unit of
movement for actors in the world.
A CrabWorld is 600 x 400 cells in size. In this case, a cell is 1 pixel.
CS2
Final exam – Review notes
3
The method of Animal:
boolean atWorldEdge()
returns true if the Animal is at the edge of the world. Otherwise, it returns false.
Below is an if statement that uses the atWorldEdge() method:
In Java, the boolean condition to be checked by the if statement is enclosed in
parentheses (). In this case, the method atWorldEdge() is called.
The method, atWorldEdge() is a predicate method. A predicate method is a method
that returns a boolean value, true or false.
The Greenfoot environment has a method that generates a random number:
Greenfoot.getRandomNumber(limit);
will generate a random number between 0 and limit – 1. The limit is not included.
For instance Greenfoot.getRandomNumber(20) will return a number between 0
and 19.
This notation is called dot notation.
To use a method of another class, the class or object name followed by a “.” Is used
before the method name.
The method getRandomNumber() is in a class called, Greenfoot.
Depending on how the method is written, it belongs to either a class or an object.
From the API, we can tell if the method belongs to a class or an object.
Below is the documentation for the getRandomNumber(int limit) method of the
Greenfoot class:
CS2
Final exam – Review notes
4
The word, static, means belonging to the class. If the header for a method contains the
keyword, static, the method belongs to the class. It must be called using dot notation
and prefaced by the class name.
Greenfoot.getRandomNumber(20);
Java has comparison operators which return true or false and can be used in the
condition of an if statement. They are:
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal
!= not equal
For example:
if (x < 6)
if (x==9)
Class names always start with capital letters by convention. Spaces are not allowed in
names in Java. If you want more than one word in the class name, each word is strung
next to each other and capitalized. For example, LittleBear. This naming convention is
called PascalCase.
It is good programming to break down methods into smaller methods so they are easier
to understand and find errors. The Crab’s act method below can be broken down:
CS2
Final exam – Review notes
5
Three new methods definitions can be added to breakdown the act method of the
Crab:
The methods name are: lookForWorms(), randomTurn(), and turnAtEdge():
These methods are new methods of the Crab class.
New methods are made after the closing bracket “}” for the act method and before the
closing bracket “}” for the class.
All of these methods are public
The next keyword is void, boolean, int (and other types we haven’t discussed yet),
depending on whether the method does a task but does not return a value (void,
like a command block), returns a boolean (boolean, like a predicate block) or
returns another value (so far, int, like a reporter block).
All three of the methods we created are void.
Writing the definition for the methods does not run them. In order to run the code
inside the methods, the methods must be called.
CS2
Final exam – Review notes
6
We delete all the statements from inside the act() method and added method calls:
Note that by convention, method names start with lowercase letters. Spaces are not
allowed in names. If multiple words are used, they are written in camelCase.
Names written using the camelCase naming convention, start with lowercase. Every
other word in the name starts with an capital letter. For example: turnAtEdge();
The Greenfoot class has a method, boolean isKeyDown(String key)
It is a static method which means that it belongs to the class and must be called using
the name of the class with dot notation:
if (Greenfoot.isKeyDown(“left”))
It requires a parameter of type, String. A String is a data type like int or boolean.
It is the name given to a sequence of characters following each other and enclosed in
double quotes, “left”, “123Hello”, “Hello World” are all examples of Strings.
In this case, the String parameter is the name of a key on the keyboard, “up”, “down”,
“left”, “right”, “a”, etc.
CS2
Final exam – Review notes
7
If the key is down (has been pressed) the method will return true. Otherwise, it will
return false.
We added a method checkKeyPress() to the Crab class. If the “left” key is pressed, it
makes the crab turn left (negative degrees). If the “right” key is pressed, it makes the
crab turn right (positive amount):
We changed the act method to call the methods:
This made the crab turn left or right depending on the key pressed.
The Greenfoot class has a method which ends a project.
We changed the lobster class to end the project when it ate a Crab. :
CS2
Final exam – Review notes
8
The Greenfoot class has a method which plays a sound wav file.
We changed the Crab class to play a sound when it ate a Worm:
In order for this to work, the slurp.wav file must be in a sub-folder, sounds, in your
project.
Whenever a change is made to your code, the class and project must be compiled.
When a Java program is compiled, it is run through a program called a compiler.
Many programming languages have compilers.
A compiler looks at the code to see if there are any syntax errors.
Examples of common syntax errors are: a grammar error, misspelled word, missing
semicolon, unbalanced parenthesis, unbalanced brackets, missing parameter values.
All the syntax errors in a program must be eliminated before a program can be run.
The compiler converts the program written in a high-level language, like Java, that
humans can understand into a digital format that your computer can understand and
run.
CS2
Final exam – Review notes
9
Unit 2
Structure of a class
According to our class convention, classes have the following format:
public class classname
{
Instance variables
Constructors
Methods
}
The first line is the class header.
o It is the start of the program.
o The class name is followed by begin and end brackets { }
o All the statements in the program are written inside the brackets.
If a class is a subclass of another class (for example, Crab is a subclass of Animal), the
keyword, “extends” is used.
o General form:
public class subClassName extends superClassName
o Specific example:
public class Ball extends Actor
An object is created from a class.
o The class is the definition for an object type.
o Many objects can be made from one class.
o The class is the “cookie-cutter”. The cookies are the objects.
The term, instance, means object. An instance of a class is an object of the class.
An instance variable is used to store information about objects. The Instance
variables of the class are defined right after the class header:
The Ball class has one instance variable, imageNumber.
CS2
Final exam – Review notes
10
Instance variables are created using the keyword, private. One class cannot access
the instance variables of another class.
The type of the variable follows the keyword, private. All variables in Java must have a
type.
Variable types fall into two categories: primitives and objects.
o The primitives are: int, double, boolean.
An int is an integer. A variable of type int can store whole number values.
A double is a decimal. A variable of type double can store any number
with a decimal value.
A boolean can store true or false.
o The Object types are any class written or any class built into Java.
For example, String, Actor, World, Bug, Ball are all object types.
A programmer can write a class to define new Object types.
An instance variable can be used inside every method of the class.
At the very beginning of every Java class in Greenfoot there is an import statement:
import greenfoot.*;
Java classes are organized into collections of related classes called “packages”.
The greenfoot package contains many classes used in Greenfoot projects, such as World
and Actor. The import statement tells the compiler where to find the World and Actor
classes that are provided with Greenfoot. Without it, a Greenfoot class will not compile.
Comments are used in a class to provide English like explanations for other
programmers and also to remind the original programmer of what the code does.
There are three types of comments:
o Single line comments can be placed anywhere in a Java class. A single line
comment can be on a line by itself or placed after code. They start with “//”. For
example:
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
o Multiple line comments begin with “/*” and end with “*/”. For example,
CS2
Final exam – Review notes
11
/* this line will make the Ball turn a random number
of degrees between 0 and 14 */
turn(Greenfoot.getRandomNumber(15));
o Javadoc comments begin with “/**” and end with “*/”. They are placed at the
beginning of a class and methods. They provide a description of the class and
each methods:
/**
* Write a description of class Ball here.
*
* @author (your name)
* @version (a version number or a date)
*/
A constructor is a special method with the same name as the class. It has no return
type. It runs when an object is created.
The job of the constructor is to set up the object and initialize the instance variables of
the class.
According to our class conventions, the constructor is added as the first method in a
class.
The default constructor is a constructor with no input.
If a programmer does not code a constructor in a class, the compiler inserts one at
compile time that does nothing. You cannot see it but it is in the compiled version of the
class.
Every class has a constructor. The constructor runs when an object of the class is
created.
The Ball class has two constructors:
o The default constructor requires no input.
o A second constructor is used to set the rotation of the Ball.
CS2
Final exam – Review notes
12
A class can have one or more method definitions.
The act method is added automatically to every Greenfoot Actor. The act method
defines what a Greenfoot Actor does.
The act method of the Ball class defines what a Ball does when it acts:
o It moves 4 pixels in the direction (rotation) which it is facing.
o If it is at the edge of the world, it turns and changes color by changing images.
CS2
Final exam – Review notes
13
The Ball class has two method definitions:
o boolean atWorldEdge()
o void changeImage()
The atWorldEdge() checks to see if the Ball is at the edge of the world:
o It has a return type of “boolean”. The return type is written in the method
definition before the method name.
o The return statement returns a value and ends the method. It is similar to the
report block in BYOB.
o The method checks the x and y position of the Ball to see if it is at the edge of
the world. If it is, the method returns true. Otherwise, it returns false:
CS2
Final exam – Review notes
14
If the return type of a method is void, the method cannot return a value.
If the return type of a method is not void, the method must contain a return statement
which returns a value of the same type as the return type of the method.
The changeImage() method changes the image of the ball:
o It concatenates the value of the instance variable, imageNumber, to format the
name of the ball images: button-0.png, button-1.png, button-2.png,
button-3.png, button-4.png.
The “+” symbol is used to join multiple Strings into one string. It is similar to
the join block in Scratch. Joining Strings into one is called String
concatenation.
o It sets the image to the next image.
Every begin bracket must have a matching end bracket { }
Every begin parentheses must have a matching end parentheses ( )
Every statement other than a class header (first line of program), method header (first
line of the method definition) or an “if” statement must end with a semicolon ;
All method calls must have beginning and ending parentheses ( ) following the method
name.
If the method does not require input, there are no values inside the parentheses. For
example:
changeImages();
CS2
Final exam – Review notes
15
If the method requires input, the input values are provided inside the parentheses.
setRotation(170);
If the method requires more than one input value is required, the input values are
provided inside the parentheses and separated by commas.
addObject(theBall, 85, 100);
Variables
Variables in Java are the same concept as variables in VB, Scratch or BYOB.
A variable is a storage location in your computer which is given a name so a program
can store (remember) a value.
When each object of the class must have its own copy of a variable, instance variables
are used.
Local variables are defined inside a method and can only be used inside the method in
which they are defined.
A Java local variable is like a “script variable” in Scratch or BYOB. A script variable can
only be used inside the block in which it is defined.
The statement below defines a variable of type Ball:
Ball theBall;
Objects can be created using programming statements. The statement below Creates a
new Ball:
new Ball();
The keyword “new” in Java always means “create an object”.
The statement below both defines a variable of type, Ball, and creates a ball object all
on one line:
Ball theBall = new Ball();
CS2
Final exam – Review notes
16
The addObject method of the world is used to add an Actor to the world. Its general
syntax is:
addObject(Actor object, int x, int y)
Below is the constructor of the MyWorld class of Ball:
The variable, theBall, was defined inside the constructor of the MyWorld class. It is a
local variable. It can only be used inside the constructor (method) in which it was
defined.
Adding an Actor to the World from an Actor class
In the Turtle class, whenever the Turtle ate a Bug, a new Bug was added to the World.
Since only the World can add new objects to itself, the Turtle has to get its World and
then ask the world to add the object.
A local variable of type World was used to store the reference to the World.
World theWorld = getWorld();
The variable, theWorld, was used to ask the world for its width and height. The width
and height of the world were stored in the local variables, width and height:
int width = theWorld.getWidth();
int height = theWorld.getHeight();
The width and height variables were used to place the bugs at a random location in the
World. Below is the code used:
CS2
Final exam – Review notes
17
Counters
Variables are often defined in programs to keep count, such as to count the number of
points when keeping score.
Below is the definition of the points variable in the Turtle class:
It is an instance variable (declared with the keyword, private).
The constructor initializes the variable to zero. Initializing a variable means setting its
initial value.
To add 1 to the points variable, one of the two statements below can be used:
points = points + 1; //can be used to add any number to points
or
points++; //can only be used to add 1 to points
CS2
Final exam – Review notes
18
Below is the code in the tryToEat() method of the Turtle class. It adds 5 to points, if the
Turtle eats a Bug. It adds 1 to points, if the Turtle eats a Lettuce.
Unit 3
Detecting a mouse click on the world
The logic used to detect where a mouse was clicked on the world is:
o Use the mouseClicked() method of the Greenfoot class to check whether the
mouse was clicked.
o If it was, use the getMouseInfo() method of the Greenfoot class to get a
MouseInfo object.
o Use the getX() and getY() method of the MouseInfo class to get the x and y
coordinates of where the mouse was clicked.
The mouseClicked() method of the Greenfoot class is used to detect if the mouse was
clicked. It can be used to check if the mouse was clicked anywhere or on a specific
actor.
CS2
Final exam – Review notes
19
To detect if the mouse was clicked anywhere, an input value of null is passed to the
mouseClicked() method.
In computing, null has a special meaning. It means the “absence of value”.
The Greenfoot.getMouseInfo() method returns a MouseInfo object.
A MouseInfo object has a getX() and a getY() method which return the x and y
coordinate on the world where the mouse was clicked.
The code below was written in the act() method of the MyWorld class. It checks if the
mouse was clicked on any object (input value is null). If the mouse was clicked, it does
the following:
o Creates a Ball object facing in a random direction.
o Creates a local variable, mouse, of type MouseInfo object.
o It gets a MouseInfo object using the getMouseInfo() method and stores it in the
the variable, mouse.
o It uses the getX() and getY() method of the MouseInfo class to get the x and y
coordinates of the mouse.
CS2
Final exam – Review notes
20
o Uses the x and y coordinates to add a Ball object to the world at that position.
Changing the background color of the world
The logic used to change the background color of the world is:
o Use the getBackground() method of the World class to get the
GreenfootImage object used as the background image.
o Use the setColor() method of the GreenfootImage to change the drawing color.
o Use one of the pre-defined constants of the Color class in the java.awt.color
package as input to the setColor() method.
o Use the fill() method of the GreenfootImage to fill the image with the drawing
color.
At the very beginning of every Java class in Greenfoot there is an import statement:
import greenfoot.*;
Java classes are organized into collections of related classes called “packages”.
The greenfoot package contains many classes used in Greenfoot projects. The import
statement tells the compiler where to find the classes provided with Greenfoot that are
CS2
Final exam – Review notes
21
not in your project. Without the import statement, a Greenfoot class will not compile.
All images used in Greenfoot are of type GreenfootImage.
Methods of the GreenfootImage class can be used to manipulate the image, add
animations and change the background color of the world.
To change the background color of the world from white to black, the getBackground()
method of the World is used.
The getBackground() method returns a GreenfootImage which is the background
image of the world.
The GreenfootImage class has a method, setColor(). The setColor method is used to
set the current drawing color.
The setColor method requires an input parameter of type java.awt.Color.
Color is a class in the Java API which can be used to represent a color digitally. It has
many constants that can be used as a color name. Some of the color names are shown
below:
CS2
Final exam – Review notes
22
The color names of the Color class can be used as input to the setColor() method. The
code below uses setColor to change the drawing color to black for the background image
of the world. It then fills the image with the drawing color:
The class will not compile. The Color class is neither in the greenfoot package nor in the
default Java library.
If a project uses methods of other classes that are not in the project and not in the
greenfoot package, then import statements for the other packages are needed. In
order to use the Color class an import statement for the color package is needed:
CS2
Final exam – Review notes
23
import java.awt.color;
Adding the package statement will correct the compiler error.
An object is an instance of a class. The words instance and object mean the
same thing.
There are methods that belong to classes and methods that belong to
instances of classes or objects.
Methods that belong to classes are called class methods. Class methods are static.
An object is not needed in order to use a static method.
All the methods of the Greenfoot class are static. They are class methods.
The API documentation for the Greenfoot class shows that its methods are static:
The best way to know if a method is a class method (static method) is to check
the API definition for the method. If the keyword static is shown in the API
documentation for the method, then it is a class method.
All the methods of the Greenfoot class are static and must be called preceded by the
class name. They are class methods.
All the methods of any of the other built-in classes such as Actor and World are
instance methods and must be called preceded by a variable of type object.
Moving an actor with setLocation
The move method of the Actor class moves an actor in the direction it is facing.
The top left corner of the world is location (0,0).
CS2
Final exam – Review notes
24
The logic to move an actor without regards for its current direction when a key is
pressed is:
o Use the isKeyDown() method of the Greenfoot class to check if a key was
pressed.
o Get the x or y coordinate of the current location of the actor using the getX()
and getY() methods of the Actor class.
o To move an actor up in the world, subtract from its y coordinate.
o To move an actor down in the world, add to its y coordinate.
o To move an actor to the right in the world, add to its x coordinate.
o To move an actor to the left in the world, subtract from its x coordinate.
o Use the setLocation() method of the Actor class to change the location to the
new x and y coordinates.
Below is a checkKeys() method which can be used to do this:
The checkKeys() method must be called in order for it to work.
CS2
Final exam – Review notes
25
Checking the edge
When moving an actor up, down, left and right, when the actor hits the edge, half of the
object moves outside of the world beyond the edge.
The following logic can be used so that the actor “bounces” off the edge and is entirely
in the world:
o If when the actor moves to the right, its x coordinate is greater than the width of
the world minus 20 pixels, move the actor 20 pixels to the left.
o If when the actor moves to the left, its x coordinate is less than 20, move the
actor 20 pixels to the right.
o If when the actor moves up, its y coordinate is less than 20, move the actor 20
pixels down.
o If when the actor moves down, its y coordinate is greater than the height of the
world minus 20 pixels, move the actor 20 pixels up.
Below is a sample checkEdge() method that was written to do this:
This method must be called after checking for a key press or it will not work.
Detection collision and removing an actor
The canSee() and eat() method of the Animal class were used to detect when two
actors collided and to then remove one of them.
CS2
Final exam – Review notes
26
Methods of the Greenfoot class and the World class can be used to do the same thing:
o The getOneObjectAtOffset () method of the Actor class is used to get one
object at the same cell as this object.
o The removeObject() of the World class is used to remove the actor.
The getOneObjectAtOffset() method returns one object that is located at a cell with
the offset given, relative to this object’s location.
When 0, 0 is used as the x and y offsets, it returns an actor which is at the same cell in
the world as this object.
If there are no Actors at the cell where this Actor is located, getOneObjectAtOffset()
returns null.
Below is the code written to remove any Pizza objects in the same cell as the Woman
object in the Woman class:
Notice that the variable, aPizza, is of type Actor. This is because any type of object
could be found in the same cell as this actor. The getOneObjectAtOffset method always
returns an Actor.
The symbol, != , means not equal in Java.
The method getOneObjectAtOffset returns null if there are no Actors in the same cell as
this actor.
In computing, null means “the absence of value”.
An Actor referring to itself
The keyword, this, means the current actor. It is used in actor classes to have an actor
refer to itself. For example, to have a Bee object refer to itself.
CS2
Final exam – Review notes
27
The mouseClicked() method of the Greenfoot class was used to detect where the
mouse was clicked on the world.
The mouseClicked() method can also be used to detect if the mouse was clicked on an
actor.
The code below written in an actor class (for example, Crab, Pizza, etc) is used to detect
if the mouse was clicked on the current actor. It also asks the world to remove the
actor:
The keyword, this, is used as input to mouseClicked(). If the mouse was clicked on the
current actor, the method will return true. Otherwise, it will return false.
If the mouse was clicked on the actor, the actor will ask the world to remove it.
Boolean and relational operators
The relational operators are used to compare two operands. The operands can be
primitive numeric values, variables of primitive number types (int, double) or arithmetic
expressions. The relational operators in Java are:
< less than
> greater than
<= less than or equal to
>= greater than or equal to
== equal to
!= not equal to
The symbol && in Java means AND.
The symbol || in Java means OR.
The boolean operators, && and || , are used to combine boolean expressions.
CS2
Final exam – Review notes
28
In order for a boolean expression containing || to be true any (either or) of the
conditions combined with the || must be true individually.
The condition in the “if” statement below will evaluate to true if the getX() method
returns a value which is either less than 10 or greater than the width of the world – 10.
If any of the individual conditions combined with the || (or) symbol is true, the
condition in the” if” statement will evaluate to true.
In order for a boolean expression containing && to be true both of the conditions
combined with the && must be true individually.
The condition in the “if” statement below will evaluate to true if the getX() method
returns a value which is both greater than or equal to 10 and less than or equal to the
width of the world – 10. If both of the individual conditions combined with the &&
(and) symbol is true, the condition in the” if” statement will evaluate to true.
Unit 5
Loops are used in programming to avoid repeating programming statements
that perform the same task.
In CS1, you used the “Repeat n times”, “Forever” and “Repeat until” blocks.
These were examples of loops.
Another name in Computer Science for a loop is “Iteration “.
The types of loops used in this unit are: while loops and for loops.
A “boolean expression” is used to control a loop. A “boolean expression” is a
statement that evaluates to true or false, for example (x < 6).
Using a while loop, the statements inside the loop will execute for as long as the
condition of the loop is true. The loop will stop when the condition becomes
false
CS2
Final exam – Review notes
29
Below is an example of a while loop:
The loop above does the following:
o Creates a variable of type int, count. It sets the value of count to zero
before the loop starts.
o The condition controlling the loop is “count < 20”. The condition is
enclosed in parenthesis (same as for an “if” statement).
o The statements that will run for as long as the condition is true are coded
inside begin and end brackets { }.
o The statements inside the brackets are called the “body” of the loop.
o The value of count must be changed inside the body of the loop or the
loop will run forever.
o The statement count++; adds 1 to count each time the body of the loop
runs.
o The loop will run when count is equal to 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18 and 19 for a total of 20 times.
A loop that runs forever is called an “infinite” loop. This would happen if we
forgot to include count++; in the body of the loop.
A “for” loop is another type of iteration statement. Below is an example of a
for loop:
CS2
Final exam – Review notes
30
A for loop has 3 parts:
o The initialization (int i = 0); defines and initializes the variable that will
control the loop. In this loop, the controlling variable is named, “i”. By
convention, i and j are often the names of the variable used to control
loops. But this is not a requirement.
o The condition i < 10; defines the condition that controls the loop. The
statements inside the loop will run for as long as the condition is true.
o The increment or decrement i++ adds or subtracts from the variable
that controls the loop.
o The initialization and the condition are followed by semicolons.
o Any number can be added or subtracted from the variable that controls
the loop. In this example, the variable is named, i.
o To add one to the variable, use:
i++ or i+=1
o To add more than one, use:
i+=n is used, for example: i+=2
o To subtract use:
i-- or i-=n for example: i-=2
CS2
Final exam – Review notes
31
o The loop will run when count is equal to 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 for a
total of 10 times.
Below is an example of a loop that can be used to print all the even numbers
written as a while loop and as a for loop:
for (int i = 2; i <=10; i+=2)
{ System.out.println(i);
}
int i = 2; while ( i <= 10)
{ System.out.println(i);
i+=2; }
o The while loop and for loop do the same thing. They print the even
numbers starting at 2 and ending at 10. The loop runs when i is equal
to 2, 4, 6, 8, 10 for a total of 5 times.
An Array is an object that can hold multiple variables. The values of the
variables can be accessed using an index.
The code below will define an Array of Strings that can hold the names of image
files fruit objects:
String [] fruitName = {“apple1.png”, “apple2.png”, “bananas.png”,
“cherries.png”, “grapes.png”, “orange.png”};
The variable, fruitName, is used to refer to the Array. We can visualize the
Array in the computer’s memory this way:
fruitNames
“apple1.png” “apple2.png” “bananas.png” “cherries.png” “grapes.png” “orange.png”
The values (fruit names) of the Array are specified using an initializer list.
There are 6 names of fruit image files in this array. Since the names are String
values, they are enclosed in “ ” .
The length of an array is the number of elements in the Array. The length of our
fruitName array is 6.
CS2
Final exam – Review notes
32
To find the length of the fruitNames array, we can use the length property of
the Array:
fruitNames.length
The first element is at position 0, the second at position 1, the third at position
2, and the last at position 5.
To access the value at the first position in the Array, we code:
fruitNames[0]
To access the value at the last position in the Array, we code:
fruitNames [5]
The number inside the [] is called the index. The value of the index starts at 0
and ends at length -1.
The fruitNames array has a length of 5. The first index value is 0 and the last
index value is 4.
The code below uses the fruitNames Array:
The loop starts with i = 0 and stops when i is equal to the length of the array
(6).
CS2
Final exam – Review notes
33
The loop runs when i is equal to 0, 1, 2, 3, 4, or 5. Each time that it runs:
o A Fruit object is created having as its image the image file, fruitName[i].
o The fruit object is added to the world at a random position.
If a coding mistake is made and the loop runs when i is equal to 6, the program
will blow up with an “ArrayIndexOutOfBoundsException” error since there is
no element at position 6 in the Array.
System.out is used to print in Java. The method println print whatever input
parameter is passed to it and then skips a line.
To print a blank line use:
System.out.println();
Methods used so far – all the methods and what they do are in the API which you
will have during the test. There is no need to memorize the syntax.
Methods of Actor:
void act() Runs once when the Act button is pressed.
Runs until the project stops when the Run
button is pressed.
int getX() Returns the x coordinate of the Actor’s
position.
int getY() Returns the y coordinate of the Actor’s
position.
GreenfootImage getImage() Returns the current GreenfootImage for the
Actor.
CS2
Final exam – Review notes
34
void setImage(GreenfootImage img)
void setImage(String fileName)
Used to change the image of an Actor. It
can take a parameter of type
GreenfootImage or String. If the
parameter is a String, it is the image file
name.
int move(int x) Moves an Actor x number of units
int turn(int x) Turns an Actor x degrees
void setRotation(int direction) Sets the rotation (direction of this Actor to
a number between 0 and 360. A rotation of
zero means that the Actor is facing to the
Right. The numbers of degrees increase
clockwise. A rotation of 90, means that the
Actor is facing down.
void setLocation(int x, int y) Assigns a new location to this actor. This
moves the actor to the new location.
Actor getOneObjectAtOffset(int dx, int dy,
java.lang.class clss)
Returns one object that is at the specified
cell in relation to this actor’s location. If
0,0 is used for dx and dy, it returns an
actor in the same cell as this actor.
Methods of World:
int getWidth() Returns the width of the World
int getHeight() Returns the height of the World
GreenfootImage getBackground() Returns the GreenfootImage used as the
background for the world.
void setBackground(GreenfootImage img) Sets the background image of the world to
the GreenfootImage passed as parameter.
void addObject(Actor a, int x, int y)
Adds object at position x, y
void removeObject(Actor a) Removes the object passed as input from
the World.
Methods of Greenfoot class:
static boolean isKeyDown(String keyName)
Example:
if ( Greenfoot.isKeyDown(“left”) )
Returns true if the key has been pressed
static int getRandomNumber(int limit)
Example:
move( Greenfoot.getRandomNumber(11) );
//returns a random number between 0 and 10
Returns a random number between 0 and 1
less than limit
CS2
Final exam – Review notes
35
static void playSound(String filename)
Example:
Greenfoot.playSound(“au.wav”);
Plays a sound file
static void stop()
Example:
Greenfoot.stop();
Stops the project
static boolean mouseClicked(java.lang.Object obj)
Example:
if ( Greenfoot.mouseClicked(null) )
Return true if the mouse was clicked on the
object (actor) passed as input. If null is
passed as input returns true if the mouse
was clicked on the world. If the mouse was
not clicked, it returns false.
static MouseInfo getMouseInfo()
Example:
MouseInfo mf = Greenfoot.getMouseInfo();
Returns a MouseInfo object containing
information about the mouse after it is
clicked on the world or an actor in the
world. It returns null if the mouse is outside
of the world or not clicked.
Methods of the MouseInfo class:
int getX() Returns the current x position of the mouse
cursor.
int getY() Returns the current y position of the mouse
cursor.
For the final exam, you should know the following:
o How to create and save a Greenfoot project.
o How to create a subclass of World and Actor
o How to print a line of text
o How to write a while loop
o How to write a for loop
o How to set the images for the World and for Actors
o How to play a sound file
o How to stop a project
o How to write if statements
o How to write methods
o How to create Actors and add them to the world
o How to remove Actors from the world.
CS2
Final exam – Review notes
36
o How to detect if two actors are touching
o How to make actors move and or turn.
o How to detect that a key was pressed
o How to define and use instance variables
o How to define and use local variables
o How to define and use constructors.
o How to check if an Actor is at the edge of the world.
o How to generate a random number.
o How to stop a Greenfoot world.