CPT120 subject material (pdf file) - RMIT University
CPT120 subject material (pdf file) - RMIT University
CPT120 subject material (pdf file) - RMIT University
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
Introduction<br />
Introduction to Programming<br />
Chapter 1: Introduction<br />
At the completion of this weeks study, students will:<br />
Have an understanding of what is involved in using a programming language<br />
Understand the difference between methods and properties<br />
Have an appreciation of scenarios and the use of storyboards<br />
Have an understanding of the steps involved in constructing a program<br />
Understand how to write and run a simple program in Alice<br />
Co urse Materials<br />
Online Course Material<br />
Please select a subtopic to view its contents.<br />
The Alice Environment<br />
Scenarios and Storyboards<br />
Practical Exercises<br />
Practical Exercises<br />
Additional Materials<br />
Reading References<br />
Textbook: "Learning to Program with Alice", W. Dann et al., Pearson Prentice Hall.<br />
Chapter 1, pp7-14<br />
Chapter 2, pp19-37<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\01\index.html<br />
Page 1 of 1<br />
Up | Site Map<br />
Up | Site Map<br />
18/03/2008
The Alice Environment<br />
Introduction to Programming<br />
C ha p ter 1: Introduction<br />
The Alice Envi ronment<br />
Introduction<br />
Up | Site Map<br />
In this <strong>subject</strong> we will be looking at many aspects of a programming language; we will study<br />
different types of variables, IF statements, looping structures, properties and methods,<br />
functions and arrays.<br />
To accomplish these tasks, you will need three pieces of software: all free and downloadable<br />
from the web, or available on the textbook CD. Firstly, you will need a program called Alice.<br />
This is on the CD that comes with the course textbook ("Learning to program with Alice").<br />
Please note this is a Windows version only, A version for Macintosh and Linux can be<br />
downloaded from the Alice website's download page at www.alice.org. (Note: do not download<br />
"Storytelling Alice".)<br />
The Alice download page: http://www.alice.org/index.php?page=downloads/download_alice<br />
Page 1 of 5<br />
Later on in this <strong>subject</strong>, you will require the Eclipse Development platform. This is freely<br />
downloadable from the Eclipse Web site at www.eclipse.org. Download the Eclipse IDE for Java<br />
Developers; versions are available for Windows, Linux and MacOS X.<br />
When we will be studying the basics of Java, you will need a Java runtime environment (JRE). I<br />
would suggest the Sun JRE; this is freely available from Sun's Java web site at java.sun.com.<br />
The first program we will be using is Alice. This programming tool uses a graphical interface to<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\01\alice-environment.html<br />
18/03/2008
The Alice Environment<br />
build a program. We accomplish this by dragging and dropping items in order to 'build' the<br />
code. Then, by clicking on the run button, you can see instantly what your program does. We<br />
will use Alice to demonstrate all of the concepts we will be learning as part of this course.<br />
Note though, that Alice is not a commercial programming language. Alice is a language that<br />
was designed to be a teaching tool for introductory programming. The other language we will<br />
be using, Java, is a commercial programming language and uses a written syntax to program<br />
it.<br />
Why Learn Programming?<br />
The reasons why people learn how to write programs for computers are many and varied.<br />
Programming is a profitable occupation; many programmers have jobs that are highly paid.<br />
You may also need an understand the basic concepts of programming in order to work with<br />
programmers. If you understand how to use even the basic methods of programming, it will be<br />
much easier for you to describe to a programmer exactly what you require. Programming gives<br />
you experience in following a much more logical way of thinking.<br />
When we are starting to design a program, we must look at the logical steps required to<br />
complete the task. These steps must be small enough so that they can be converted into<br />
logical steps in our program code. On a personal level, when we write code it is an expression<br />
of ourselves: just as an author, when writing a book, is expressing themselves in words, a<br />
programmer is expressing their ideas and logic in the way they design and build their<br />
programs.<br />
The World and Objects<br />
Any 'world' consists of objects. Think of the room you are in now; what objects are there?<br />
Firstly there's you, maybe a chair, a desk, the computer, the mouse, the keyboard, a light on<br />
the ceiling, a light switch on the wall, and lots of other objects. Programs must be able to<br />
model these objects. By this, we mean we must be able to describe the qualities and attributes<br />
of an object.<br />
For example, we must be able to describe the objects' color, or the fact that the object has two<br />
arms. We also then have to provide methods to manipulate these qualities or attributes. With<br />
the previous examples, we must for instance have a way to be able to change the color of an<br />
object, or to raise the object's left arm. With Alice, we are able to do this directly. We can, and<br />
often have to, define much information about an object. We call this information the object's<br />
properties (qualities and attributes).<br />
Take, for instance, a chair (we'll assume it's an office chair).<br />
What parts has the chair got? The legs with castors, the seat, and the chair back.<br />
What qualities has this chair? Its height, color, <strong>material</strong> it's made of, and so on.<br />
Objects are able to do things; take our chair. what things can a chair do? The whole chair can<br />
move on the castors, the chair seat can rotate on its legs, in the computer 'world' the chair can<br />
also get bigger or smaller, or change color. We call the actions that the chair may perform, the<br />
object's methods.<br />
What is a Program?<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\01\alice-environment.html<br />
Page 2 of 5<br />
18/03/2008
The Alice Environment<br />
When we write a program, we are providing a set of instructions for the object to follow. We<br />
specify the methods an object (in this example, a dancer) must do and in what order the object<br />
must do them in. For example:<br />
dancer turn .25 revolutions right - the dancer would turn 90 degrees to the right<br />
dancer move forward 2 meter - the dancer moves forward 2 meters<br />
dancer turn 5 revolutions left - The dancer would pirouette to the left<br />
dancer move backward 1 meter<br />
In the above example, we have told the dancer exactly what to do. They must do exactly what<br />
we have specified and in the exact order. Each time we run this program the dancer will follow<br />
the same path and end up in exactly the same position, given that our starting position is the<br />
same each time.<br />
With our chair example, we could think of it as a movie script, the director (programmer) has<br />
said, "I want a dancer, I want them to start at this position, and I want them to move like this<br />
and end up here." Each time our director calls 'Action!', the same set of movements are carried<br />
out.<br />
Another way we can also think about programming is it being like a sports game. In a sports<br />
game players interact with other players around them, in the above example we could have<br />
said:<br />
I want 2 dancers starting from these positions,<br />
dancer1 turn .25 revolutions right - dancer1 would turn 90 degrees to the right<br />
if dancer1 is facing dancer2<br />
dancer1 turn .25 revolutions right<br />
dancer1 move forward 2 meter - dancer1 moves forward 2 meters<br />
dancer1 turn 5 revolutions left<br />
dancer1 move backward 1 meter<br />
In this example, the dancers interact with each other. If dancer1 is facing dancer2, dancer1<br />
turns an extra 90 degrees then continues with the rest of the program.<br />
The Alice System<br />
When you start Alice you will notice a number of distinct areas on the Alice screen.<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\01\alice-environment.html<br />
Page 3 of 5<br />
18/03/2008
The Alice Environment<br />
Page 4 of 5<br />
In the middle at the top is the World Window. This gives you a visual indication of the current<br />
world. It shows you what objects are present, and their positions and sizes. This window also<br />
allows you to add objects and to position them.<br />
Next to the World Window, on the left, is the Object Tree. This window allows you to see all of<br />
the objects present in your world, including the camera and light.<br />
Below the Object Tree is the Details Area. This window shows the selected object's properties,<br />
methods and functions.<br />
Right of the Details Area is the Editor Area. This area is where you build your program, by<br />
dragging and dropping an object's methods from the Details Window.<br />
Above the Editor Window is the Events Area. This is where you specify which events can occur<br />
in your program, and what is to be done in response to each event. When we click on the Play<br />
button, our world starts, and in the Events Area we can then specify the method we want to<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\01\alice-environment.html<br />
18/03/2008
The Alice Environment<br />
run, such as World.MyFirstAnimation.<br />
As we have seen previously, objects have properties (e.g. size, color, head, wing, ...) and<br />
methods (change size, flap wing, nod head, ...) We can see the properties of an object by<br />
clicking on it from the object tree, and then viewing the Properties tab of the details tab.<br />
In the editor area, we are able to write new methods that we can use to change an object's<br />
properties. As with an object's properties, we can also view an object's methods by clicking on<br />
the Methods tab of the details area. This area gives us a list of what the object can do. In this<br />
tab, we can also define extra methods for each object.<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\01\alice-environment.html<br />
Page 5 of 5<br />
Up | Site Map<br />
18/03/2008
Scenarios and Storyboards<br />
Introduction to Programming<br />
C ha p ter 1: Introduction<br />
Scenarios and St orybo ards<br />
Designing a Program<br />
Up | Site Map<br />
Before construction is started on any engineering work, a design is arrived at. What would<br />
happen if the mechanics started to build an aeroplane without first putting in hours of<br />
preliminary design? What if the brakes were not strong enough to stop the plane? What if they<br />
had only put in a very small fuel tank? It would be too late for modifications once it was in the<br />
air.<br />
Just as in designing an aircraft or a skyscraper, it is vitally important to design your program<br />
prior to writing the first line of code. This design process starts by looking at the tasks<br />
scenario. From this, we can find exactly what our program is meant to accomplish. We can also<br />
find from the scenario what objects are needed and what actions occur.<br />
A Scenario<br />
After traveling through space, a robot-manned craft lands on the moon. The robot<br />
sets up his camera to show the Robot, the Lander and some nearby rock<br />
formations. An alien peeks out from behind a rock and surprises the robot. the<br />
robot looks around and sees the alien and walks over for a closer look. The alien is<br />
frightened and hides behind a rock.<br />
In our the above scenario we can see that the overall task is to create a story about an<br />
encounter between a robot and an alien.<br />
what are the objects?<br />
Robot-manned craft, Robot, rocks, Alien and the moon landscape.<br />
What are the actions?<br />
Alien peeks out from behind rock<br />
the Robot is surprised<br />
Robot looks around<br />
Robot sees the alien<br />
Robot moves towards Alien<br />
Alien is frightened and hides.<br />
Page 1 of 2<br />
In the above example we are able to see exactly what objects we need to have in our 'world',<br />
the actions each object needs to be able to make and in what order the actions need to be<br />
done.<br />
When we know the who, what, when and where of our program we can then start to translate<br />
this into our code. We can get this information from our scenario and use it in the design of our<br />
program prior to writing any code. There are a number of methods we can use to design our<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\01\scenarios-storyboards.html<br />
18/03/2008
Scenarios and Storyboards<br />
programs. these include flow charting, pseudo-code and storyboarding.<br />
Storyboards<br />
With the "visual programming" that you are now starting to learn, it is important to use a way<br />
of describing your world and the events that happen in it. One type of design tool is the use of<br />
storyboards. These allow you to depict your story scene by scene. A type of storyboard called<br />
visual storyboards allow us to draw each scene in the story, allowing us to show the who, what<br />
and when in picture form.<br />
Another type of storyboard is called a textual storyboard: this is very similar to the list of<br />
actions for the alien-robot scenario. This type of storyboard gives us a breakdown of the steps<br />
we need to use in our code, and is similar to a very detailed to-do list.<br />
Do the following steps in order<br />
Alien moves up<br />
Alien says, "Slithy toves?"<br />
Robot's head turns around<br />
Robot turns to look at Alien<br />
Do together<br />
Robot moves toward the Alien<br />
Robot legs walk<br />
Alien moves down<br />
A visual storyboard from the previous scenario<br />
It is important to start now to practice using design prior to coding, even<br />
with the easier scenarios in this course, this will prepare you for harder<br />
scenarios you may encounter.<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\01\scenarios-storyboards.html<br />
Page 2 of 2<br />
Up | Site Map<br />
18/03/2008
Practical 1<br />
Introduction to Programming<br />
Chapter 1: Intr oduction<br />
Practical E x ercise s<br />
Installing Alice<br />
Up | Site Map<br />
For this session you will need to have either the CD that comes with the textbook (Learning to program with Alice).<br />
Please note this is a Windows version only, otherwise download a copy from the Alice web site's download page. Click<br />
on the <strong>file</strong> you require, and save this to your computer.<br />
If you are using the textbook CD on a Windows machine, this should automatically run. If not, open Windows Explorer<br />
and click on the CD drive icon. This will be labeled Alice 2.0. A box will then ask where you want to place the <strong>file</strong>s;<br />
select My Desktop and also select under how much would you like to copy: Minimum. After this, click on Copy Alice<br />
from CD. You will then be asked if you want a shortcut placed on the desktop, Please select yes.<br />
For those students who have downloaded a copy from the web:<br />
If you are installing the Windows copy, double click on the <strong>file</strong> called Alice.zip which you have downloaded. Once the zip<br />
<strong>file</strong> opens, select Extract. You will then be asked where to extract to, I would suggest extracting to C:\ - the program<br />
will then install to a folder called Alice. You will need to create a shortcut to the <strong>file</strong>s you have just extracted.<br />
There are two executable <strong>file</strong>s for Alice. Firstly, try making a shortcut to the <strong>file</strong> called Alice (in the directory you<br />
extracted the zip <strong>file</strong>). If this does not run correctly, try making a shortcut to SlowAndSteadyAlice as this may run<br />
better.<br />
If you are having troubles with installing, please post a message to the discussion board.<br />
Your First Alice Program<br />
Once you have installed Alice, let's get to writing your first Alice program.<br />
The scenario:<br />
Do not download the <strong>file</strong> called "Storytelling Alice". The <strong>file</strong> we require for this <strong>subject</strong> is Alice<br />
2.0.<br />
Page 1 of 5<br />
One day a cow was out walking in the field, suddenly it sees a snake in the grass and waves it's tail in fright. The cow<br />
says, "Eek!! a snake!" and then jumps up and down to frighten away the snake. The snake then slithers away from the<br />
cow<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\01\practical.html<br />
18/03/2008
Practical 1<br />
What are the Objects in our scenario?<br />
The Cow, the Snake<br />
What are the actions (Storyboard)<br />
Cow walks towards Snake<br />
Cow gets near Snake<br />
Cow waves tail in fright<br />
Cow says, "Eek!! A snake!"<br />
Cow jumps up and down<br />
Snake slithers away<br />
Now open Alice and firstly we need the two objects. Click on add objects in the World Window, at the bottom of the<br />
screen is a list of objects to select from. Click on the Animals tab and scroll across to find the cow. Click and hold the<br />
left button on the cow and drag this to the world. Drop the cow somewhere near the middle of the world screen.<br />
Likewise, find the snake and drag this to left-front of the world screen. Your World should look something like this.<br />
Click on done.<br />
The initial world with the two objects.<br />
Page 2 of 5<br />
Now we can start to add some code. Our first task is to get the cow to walk towards the snake. Click on cow in the<br />
Object Tree. Below the object tree is the Details area. Fortunately a method has already been created for us, for the<br />
cow to walk towards another object. Click and hold the WalkTowards method and drag it to the Editor area. Drop this<br />
method in the box just under the line that says no variables. You will then be asked for which object to walk towards;<br />
select the snake. For times, select other and enter 10 (you may need to adjust this to stop the cow trampling on the<br />
snake -- we don't want dead snakes in our programs!) Then you will be asked for the speed, select 1.<br />
Now you have got the first line you can run the program, click on Play in the top left corner. (Tthis is where you may<br />
need to adjust the times value to get the cow to stop just short of the snake.)<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\01\practical.html<br />
18/03/2008
Practical 1<br />
The first instruction 'WalkTowards' in place<br />
Now our next step is to get the cow to wag its tail in fright. There is a method for this in the details area, drag and drop<br />
this below the walk towards method. You will be asked for times - select 5. Now press Play to test your code. The cow<br />
walks towards the snake and stops and wags it's tail.<br />
When you place a new method in the Editor area, a green line will indicate where the new<br />
instruction will be placed.<br />
Page 3 of 5<br />
The next action we have to get the cow to do is to say, "Eek!! A Snake!". Select cow say from the details area, and drop<br />
this method under the previous methods in the Editor area. You will need to select other and enter, "Eek!! A snake!".<br />
Test this code again:<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\01\practical.html<br />
18/03/2008
Practical 1<br />
After the third instruction 'Cow say' has been inserted<br />
Page 4 of 5<br />
The next step is to get the cow to jump up and down. Drag cow move to the editor area and select up and .5. Next,<br />
select cow move again but this time select down and .5.<br />
Then we need to get the snake to slither away; click on snake in the object tree and select slide from the details area<br />
and drop this under the other methods in the editor area.<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\01\practical.html<br />
18/03/2008
Practical 1<br />
Now click on Run.<br />
Please save your work as Week01-MyFirst.a2w.<br />
Our complete program<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\01\practical.html<br />
Page 5 of 5<br />
Up | Site Map<br />
18/03/2008
Functions<br />
Introduction to Programming<br />
Week 2: Methods, Interactio n and Functions<br />
At the completion of this weeks topic students should:<br />
know how to construct methods for an object in Alice<br />
have an understanding of what events are and how to write programs using events<br />
understand how to make a program interactive.<br />
understand when to use functions<br />
understand how to write functions<br />
understand how to use functions in a program<br />
Co urse Materials<br />
Online Course Material<br />
Please select a subtopic to view its contents.<br />
Object Methods<br />
Adding Interactivity with Events<br />
Using Functions<br />
Tutorial and Practical Exercises<br />
Practical Exercises<br />
Additional Materials<br />
Reading References<br />
Textbook: "Learning to Program with Alice", W. Dann et al., Pearson Prentice Hall.<br />
Chapter 3, pp51-56<br />
Chapter 5, pp120-125<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\02\index.html<br />
Page 1 of 1<br />
Up | Site Map<br />
Up | Site Map<br />
18/03/2008
Object Methods<br />
Introduction to Programming<br />
Chapter 2: Methods, Interaction and Functions<br />
Object Methods<br />
Revision of last weeks <strong>material</strong><br />
Up | Site Map<br />
Before we proceed with this weeks topic, let's have a quick look at the important points from<br />
last week. Many of them were quite basic, but they are the foundation from which the rest of<br />
the unit builds on.<br />
We have looked at the what and why of programming. Programming is a set of steps<br />
that tell our objects what to do.<br />
We have seen something of why programming is important to learn.<br />
We also looked briefly at the tools that we will be using in the unit: Alice, a teaching tool<br />
to help us understand the basic programming techniques, and Java, a commercial<br />
programming language that will give us a feel for "real programming".<br />
Regarding "the world" and objects:<br />
We found that objects have properties; qualities that they possess and attributes they<br />
may have.<br />
We saw in the example of a chair that its properties might include height, color, the<br />
chair's legs and the seat. We then talked about what the chair's methods; what it can<br />
do. Our chair may have a method that makes it roll on the castors. It may have another<br />
method that changes it's size or color.<br />
We then went on to look at, "What is a program?"<br />
We found that a program is a set of instructions for the computer to follow. Just like<br />
with a recipe to make a sponge cake the chef must follow exactly the same steps and<br />
use exactly the same ingredients to end up with the correct result.<br />
We found that we could think of our programs in a number of ways. Firstly like a movie<br />
script. The actors must follow exactly the same instructions each time the director<br />
shouts "Action". Our programs can also act like a sports game. When a player is running<br />
for the ball they must be aware of the other players around them. The player must then<br />
act accordingly to avoid the opposition players and kick the ball only to players of their<br />
own team. Our programs can be like this in that an object can be made aware of other<br />
objects around them.<br />
We saw in the Cow and Snake demonstration that the program allowed the cow to be<br />
aware of where the snake was. In the first instruction cow walk towards there must be<br />
some code that instructs the cow which direction to move towards the snake.<br />
We had a look at the different areas of the Alice screen.<br />
Firstly the World Window that shows us the current world and the objects in it. This<br />
screen also allows us to place objects in our world.<br />
The next area we looked at was the Object Tree this gives us a list of objects present in<br />
the world.<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\02\object-methods.html<br />
Page 1 of 2<br />
18/03/2008
Object Methods<br />
From the object tree we looked at the Details area. This gives us lists of the objects<br />
properties and methods.<br />
Next to the details area we found the Editor area. This is where our programs are built.<br />
We then looked at Scenario and storyboarding. The importance of designing your program<br />
before you actually code cannot be overemphasised.<br />
It is crucially important to know the who, what, when and where of the scenario.<br />
We must know the who to know what objects we require.<br />
We must know the what, when and where to know the steps in the scenario.<br />
Which method, whether it be visual or textual, you choose to describe the design is up<br />
to you -- but it is important that you do carry out the design phase prior to writing your<br />
code.<br />
Making New Methods<br />
By now you have gone through two Alice programs: the Cow and Snake demonstration, and<br />
the chicken and the Road demonstration with Ken in the virtual lecture. Let's go back to the<br />
cow and snake demo. Observe exactly what happens when we issue the command for the cow<br />
to walk towards the snake. Which step the cow actually makes is an instruction in itself:<br />
We must get the left back leg and the right front leg to move forward at the same time.<br />
Then we must get the right back leg and the left front leg to move forward at the same<br />
time.<br />
These instructions must be repeated for each step the cow makes. Imagine if we had to put<br />
each instruction, move left back leg, move right front leg, move right back leg, move left front<br />
leg, ... !<br />
Consider a minimum of four instructions to move the cow one unit. Multiply this by the<br />
number of units needed to reach the snake (say 20 units), our program then takes 4 times<br />
20, or 80 steps to accomplish this one task. In fact there are many more steps just to get the<br />
cow to move: open the cow and snake demo from last week, click on cow in the object tree<br />
and the edit button of cow walk. Imagine having to write that number of steps each time!<br />
We can see from each step the cow makes, the directions are exactly the same. Move left<br />
back leg, move right front leg, move right back leg, move left front leg. Alice gives us a way of<br />
writing methods that allow us to encapsulate the steps that need to be repeated. If you click<br />
on the cow in the object window and look at the details window there is a button Create new<br />
method. We can then use this to create new methods for our cow.<br />
Please do the practical lesson for this week now; in this lesson we create a new method to get<br />
our cow to nod it's head.<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\02\object-methods.html<br />
Page 2 of 2<br />
Up | Site Map<br />
18/03/2008
Adding Interactivity with Events<br />
Introduction to Programming<br />
W eek 2: Me th ods, Inte rac t i on and F unctions<br />
Adding Inte rac t i vity with Ev ents<br />
Up | Site Map<br />
Up to now, we have not been able to interact with our world. Our programs have started when we press Play and ended<br />
when the code ends. There are times, though, where we do need to interact with the program. A flight simulator<br />
program (for example) needs interaction from the user, for the direction and speed of the plane.<br />
In the Events window we can define the program's response to events that may happen during the program's<br />
execution. Events may be any action, such the press of a key, the click of the mouse button, or when the world starts.<br />
We can change our cow and snake program from this week's practical to nod the cow's head when we press the space<br />
bar. Open the prac <strong>file</strong> in Alice and firstly remove the three times that we have used lowerHead from the Editor area.<br />
You can do this in two ways:<br />
1. click and hold on the method and drag it to the rubbish bin at the top; or<br />
2. right click on it with the mouse and select delete.<br />
Your code should look like this:<br />
After deleting the 'lowerHead' methods<br />
Page 1 of 2<br />
Above the Editor area is the Events window. Click on Create a new event and select When a key is pressed. Now click<br />
on any key and change this to space. Finally, click on nothing and change this to cow - lowerHead.<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\02\events.html<br />
18/03/2008
Adding Interactivity with Events<br />
Adding a new event to the program<br />
Now click on Play. Whenever you press the space bar, the cow will nod its head. Once you have finished this<br />
demonstration, please save the <strong>file</strong> (week2-interactive.a2w) as we will need it later.<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\02\events.html<br />
Page 2 of 2<br />
Up | Site Map<br />
18/03/2008
Using Functions<br />
Introduction to Programming<br />
W eek 2: Me th ods, Inte rac t i on and F unctions<br />
U sing Functions<br />
Asking Questions, Getting Answers<br />
We have seen previously that objects have properties. You have already used a few methods to manipulate these<br />
properties. In the previous example we wrote a new method to manipulate the cow's head.<br />
Up | Site Map<br />
Object functions allow us to ask a question about an object. For example, How far is the cow from the snake? Is the<br />
snake taller than the cow? In the Details area of the screen is another tab that shows the object's functions. We can use<br />
proximity functions to tell us what the object is near, or the distance to other objects. The size functions give us the<br />
dimensions of the object, or the relational dimensions. There are also functions for spatial relation and point of view.<br />
Let's go back to our cow and snake program from this week's practical lesson. This time it's getting a bit dangerous for<br />
the poor cow. When the cow gets near the snake, this time we'll get the snake to turn round and levitate (what next - a<br />
levitating snake) to look the cow in the eyes.<br />
Open the CowAndSnake program from this weeks practical. Firstly you will need to remove all code below the line<br />
where the cow says "Eek!! A snake!".<br />
Our starting point for the Functions demo<br />
Page 1 of 4<br />
At this point we need to get the snake to spin around and face the cow. Select snake from the Object Tree and then<br />
select snake turn from the Details area. Enter left and 0.5 revolutions. Now press Play and test your program.<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\02\using-functions.html<br />
18/03/2008
Using Functions<br />
Getting the snake to spin around<br />
Page 2 of 4<br />
Next, we need to get the snake to look the cow in the eye. Select snake move and select up. Select any value for<br />
height. Now we need a function that will give us the required height. Click on cow in the Object Tree, and functions in<br />
the Details area. Scroll down and select cow's height, and drop this on the height area of snake move.<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\02\using-functions.html<br />
18/03/2008
Using Functions<br />
Using a function to get the required height<br />
Page 3 of 4<br />
We can select many different parts of the object to get their height. In this case, select: cow - neck - the entire neck.<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\02\using-functions.html<br />
18/03/2008
Using Functions<br />
Select the entire neck<br />
Now press Play and test the program. In this example, we have returned the value of the height of the cow's neck from<br />
a function. We then have asked the snake to move to this height. Save your program as "Week2-functions.a2w".<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\02\using-functions.html<br />
Page 4 of 4<br />
Up | Site Map<br />
18/03/2008
Practical 2<br />
Introduction to Programming<br />
W eek 2: Me th ods, Inte rac t i on and F unctions<br />
Practical E x ercise s<br />
Please open up the cow and snake demo from last weeks practice. I have changed the scenario for this week.<br />
The Scenario<br />
Up | Site Map<br />
One day a cow was out walking in the field, it stops and waves its tail. The cow then looks down and sees the snake.<br />
The cow then says, "Eek!! A snake!", and jumps up and down to frighten away the snake. The snake slithers away from<br />
the cow. The cow looks down again, nods its head and says, "the snake has gone."<br />
What are the objects in our scenario?<br />
The Cow and the Snake<br />
What are the actions? (Storyboard)<br />
Cow walks towards Snake<br />
Cow gets near Snake<br />
Cow waves tail<br />
Cow looks down and sees the Snake<br />
Cow says, "Eek!! A snake!"<br />
Cow jumps up and down<br />
Snake slithers away<br />
Cow looks down<br />
Cow nods head<br />
Cow says, "the snake has gone."<br />
In the above scenario, the cow nods its head three times: once to look down and see the snake, then another two to<br />
make sure the snake has gone. As we saw earlier, when we are repeating the same code in a program one way of<br />
dealing with it is to write a new method. In this way, we can place the code in the method and use it each time we want<br />
to perform the action.<br />
Building the Program<br />
In the Object Tree, click on the cow. Click on Create a new method and give it a name, such as lowerHead.<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\02\practical.html<br />
Page 1 of 8<br />
18/03/2008
Practical 2<br />
Our new lowerHead method<br />
Page 2 of 8<br />
We need to get the cow to turn its head forward, wait briefly, then turn its head backward; but we need this action to<br />
be done with the neck as the hinge. Our first task is to get the head to rotate forward. Click on the + symbol next to<br />
the cow in the Object Tree. We only need to select the cow's head. The cow's head is part of the neck so click on the +<br />
next to neck. Click on head in the Object Tree.<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\02\practical.html<br />
18/03/2008
Practical 2<br />
Selecting the cow's head<br />
Now drag head turn to the Editor area. Select forward and click on other, enter .15 and click OK.<br />
Select 'other'<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\02\practical.html<br />
Page 3 of 8<br />
18/03/2008
Practical 2<br />
Press the clear button and enter .15<br />
Page 4 of 8<br />
We need this rotation to be about the neck. Select more at the end of this instruction. Select asSeenBy - Cow - neck<br />
and click on the entire neck.<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\02\practical.html<br />
18/03/2008
Practical 2<br />
Next, select wait from below the Edit area, and place this below the head turn method. Give the wait method a value of<br />
0.5 seconds. Lastly, repeat the head turn instruction, but with the direction of backward.<br />
We are now ready to use our new method. Click on the world.my first method tab and insert the lowerHead method<br />
under the cow.tailSwish method in the Editor area. Now, the cow should stop and look down to see the snake. You also<br />
need to insert the lowerHead method twice after the snake.slide method. Then get the cow to say "The snake has<br />
gone."<br />
Save your program as "week2-prac.a2w".<br />
Practical Exe rcise 2<br />
The Scenario<br />
A hare is standing in front of a large fan. The white (high) button presses by itself and the fan turns on. The breeze is<br />
so strong, the hare's ears are blown backward. However, the fan soon turns off and the hare's ears return to their<br />
original position.<br />
What are the objects in the scenario?<br />
The Hare (animals) and a Fan (objects).<br />
What are the actions? (Storyboard)<br />
High button moves down<br />
do together<br />
Fan's blades Roll (10 times)<br />
Hare's ears turn backward .25 revolutions<br />
do together<br />
wait 2 seconds<br />
Fan's blades roll (10 times)<br />
do together<br />
high button moves up<br />
Select the entire neck<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\02\practical.html<br />
Page 5 of 8<br />
18/03/2008
Practical 2<br />
off button moves down<br />
Hare's ears turn forward .25 revolutions<br />
When setting up objects in the World it may be better to use the Quad view. This gives you four<br />
views of the work; top, front and side as well as the normal world view. Use the buttons beside<br />
this view to rotate each object.<br />
The Quad view allows you to have better control over the placement of objects<br />
Page 6 of 8<br />
Firstly, you need to select the two objects. The Hare from the Animals menu and the Fan from the Objects menu. You<br />
will need to resize the fan. You can do this by right-clicking on the fan in the object browser, and clicking on Fan,<br />
methods, resize. You will need to make it about four times bigger than it is. When you are happy with the layout, click<br />
on done.<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\02\practical.html<br />
18/03/2008
Practical 2<br />
Resizing the fan<br />
The first action we need is to get the high switch on the fan to move down. Click on the + next to fan in the object tree,<br />
and click on high button. Drag the method for high button, move to the editor area and select down. Select .5 meters<br />
for the distance. Now we need to use the methods for what happens when the on switch is pressed.<br />
When we need to get two or more actions happening at the same time, there is a do together<br />
method. Select this from the area at the bottom of the Editor area.<br />
Page 7 of 8<br />
We now need the fan's blades to roll, and the hare's ears to move back -- but we need to have these happen at the<br />
same time. Drag a do together method from the bar below the Editor area, and place it below the switch move down<br />
instruction.<br />
Now in the do together method we can place all of the instructions that we want to happen at the same time. We need<br />
the fan's blades to roll, and both of the hare's ears to turn backward. Click the + next to fan in the object tree and<br />
select blades. In the fan blade's methods you will find a roll method. drag this to the do together box. Select roll, other<br />
and enter 10.<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\02\practical.html<br />
18/03/2008
Practical 2<br />
Select ear turn<br />
We now need the hare's ears to move backward. Click on the + next to hare, then neck and head. Select left ear in the<br />
object tree and then select turn from the method window. Select backwards and .25 revolutions. Drop this into the do<br />
together box. Do the same for the right ear method, now test your program.<br />
We now need to get the fan's blades to continue turning for a short time. Select fan, blades and drop the roll method<br />
below the do together box. enter other and 40 revolutions. Now you will need to move the appropriate switches and<br />
move the hare's ears to the original position (Hint: you may need to use another do together)<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\02\practical.html<br />
Page 8 of 8<br />
Up | Site Map<br />
18/03/2008
Chapter 3: IF Statements<br />
Introduction to Programming<br />
Chapter 3: IF Statements<br />
At the completion of this weeks topic students will:<br />
Have an understanding of if statements<br />
Have an understanding of if-else Statements<br />
Have an understanding of nested if statements<br />
Be able to apply these concepts to a programming language<br />
Co urse Materials<br />
Online Course Material<br />
Please select a subtopic to view its contents.<br />
IF Statements<br />
Nested IF Statements<br />
Tutorial and Practical Exercises<br />
Tutorial Exercises<br />
Practical Exercises<br />
Additional Materials<br />
Reading References<br />
Textbook: "Learning to Program with Alice", W. Dann et al., Pearson Prentice Hall.<br />
Chapter 3, pp62-64<br />
Chapter 6, p161-167<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\03\index.html<br />
Page 1 of 1<br />
Up | Site Map<br />
Up | Site Map<br />
18/03/2008
IF Statements<br />
Introduction to Programming<br />
Chapter 3: IF Statements<br />
IF Statements<br />
Revision of Last Week's Material<br />
We learnt about making new methods.<br />
Up | Site Map<br />
When we needed to make our object carry out a new task or if the task was repetitive,<br />
like our cow walking.<br />
We could create a method to accomplish a single task, and include the new method in<br />
our program.<br />
We also learnt about how to make our programs interactive; that is, how to respond to<br />
commands from the user, like a key press or mouse click.<br />
Lastly, we saw how to use functions in our programs. We learnt that functions are a way<br />
of getting information about an object, such as its height or distance from another<br />
object.<br />
IF Statements<br />
We use if statements every day of our lives:<br />
If it is raining, I will take an umbrella.<br />
If the lift is there when I arrive at work, I'll catch it; else I'll walk up the stairs.<br />
There are many times in our daily lives where we need to make a decision based on some<br />
fact. Likewise, in our programs, we are constantly having to make decisions based on<br />
information within the program.<br />
Page 1 of 3<br />
We can think of this as the "sports game" type programming we mentioned in week one. A<br />
player who has the ball has constantly to make decisions; "Where is the nearest player in my<br />
team?", "Where is the nearest player in the other team?", "Am I close enough to the goals to<br />
score?", and so on. The player needs to make choices based on the answers to these<br />
questions.<br />
For example: "If I am close enough to the goal to score, I'll kick the ball towards the goal." In<br />
this example, we "kick the ball towards goal" IF the TEST "I am close enough to score" is<br />
TRUE. If the test is false, then we don't kick the ball. We can see from this diagram the flow of<br />
the program; notice that there are two paths from the test statement. One, yes, carries out<br />
the required task "Kick the ball". The other, no, skips this instruction.<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\03\if-statements.html<br />
18/03/2008
IF Statements<br />
We can also say what to do if the test failed. In the previous example, what would our player<br />
do if "I am close enough to score?" is false? They need to have another action. Maybe they<br />
should kick the ball to another player on the same side.. our if statement then becomes<br />
If I am close enough to the goal to score<br />
I'll kick the ball towards the goal<br />
else<br />
The flow of an if statement<br />
I'll kick the ball to another player on my side<br />
Page 2 of 3<br />
The new if statement takes into account both of the possibilities for our test. If the test is<br />
TRUE - I'll kick the ball towards the goal. If the test is FALSE - I'll kick the ball to another<br />
player on my side. The next diagram shows the If - else scenario. If oru test is yes (TRUE) we<br />
do one action. Whilst if our test is no (FALSE) we do another action.<br />
We can also use functions in our test to get information on an object. For example, if we need<br />
to make a decision based on the color of an object, such as telling if a ball is red or green:<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\03\if-statements.html<br />
18/03/2008
IF Statements<br />
if ball.color == red<br />
cow say "the ball is red"<br />
else<br />
cow say "The Ball is green"<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\03\if-statements.html<br />
Page 3 of 3<br />
Up | Site Map<br />
18/03/2008
Nested IF Statements<br />
Introduction to Programming<br />
Chapter 3: IF Statements<br />
Nested IF Statements<br />
Up | Site Map<br />
Sometimes our scenario might require us to make a decision, based on a previous decision. In the example of<br />
the football player discussed earlier, the player made a decision of, "If I am close enough to goal to score, I'll<br />
kick the ball towards goal; else, I'll kick the ball to another player on my side." What happens, though, if the<br />
goal being kicked to is the opposition's goal, or there is no other player to kick the ball to?<br />
In this case, we need to include more if statements. "If the goal I'm kicking to is the opposition's goal, I'll turn<br />
around and kick the ball to a player on my side; else, I'll kick the ball towards goal."<br />
If I am close enough to the goal to score<br />
If the goal is my team's goal<br />
I'll kick the ball towards goal<br />
else<br />
else<br />
I'll turn around and kick the ball to someone on my team<br />
If there is a team member on my side close enough to click to<br />
else<br />
I'll kick the ball to that player<br />
I'll run and bounce the ball in front of me till I find a player on my side<br />
As you can see, programs can become complex fairly quickly. The above example is only nested two levels;<br />
imagine if statements were nested five (or more!) levels.<br />
Mana and Zombie<br />
The "Mana and Zombie" example we'll go through now, will further explain the need for nested loops.<br />
The Scenario<br />
You will notice in the above example that each section of the if statements are indented.<br />
This is important, as it gives you an indication of the actions that belong to each section.<br />
Page 1 of 5<br />
Mana is a short-sighted child who can see dead people. She can turn left (left arrow key) and move forward<br />
(space key). If a zombie is within 0.5 meters in front of mana, she says, "I see dead people."<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\03\nested-if.html<br />
18/03/2008
Nested IF Statements<br />
Mana and the Zombie.<br />
We have learnt earlier that we can create new methods, and use these new methods in events. Our solution to<br />
getting Mana to respond to the required key presses may be:<br />
The mana.forward and mana.turnleft methods.<br />
Go ahead and try this scenario. Unfortunately we have a problem with Mana moving; she can walk right<br />
through the Zombie.<br />
We can walk Mana right through the Zombie.<br />
Ok, let's change our mana.forward method so that she can only move to within .25 meter of the Zombie --<br />
we'll need an if statement for this. If mana is greater than .25 meters in front of the zombie, she will be able to<br />
walk.<br />
We need to build this test. The value required in this case is the distance that the Zombie is in front of Mana;<br />
and to test if this value is less than .25 meters.<br />
The modified mana.forward method.<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\03\nested-if.html<br />
Page 2 of 5<br />
18/03/2008
Nested IF Statements<br />
We have another problem with our modified method. What happens if Mana is behind the Zombie? We have<br />
only said that Mana can walk if she is in front of the Zombie, at a distance greater than .25 meters. If Mana<br />
moves behind the Zombie, she will not be able to move any further. In this case, the if statement would fail<br />
and the move instruction would be skipped over.<br />
We need to change the test again. This time we need to take into account if Mana is in front of the Zombie and<br />
if the distance in front is less than or equal to .25 meters. If both of these tests are true, then we need to stop<br />
Mana from walking any further forward. For this we need to use a both a and b logic (in World functions). The<br />
first test, Zombie is in front of Mana, needs to be added to the a area of the logic construct. For the other test,<br />
we first need a less than or equal to math function (in World functions). We should then drop into this the<br />
zombie distance in front of mana function. Our modified mana.forward function then becomes<br />
We could also use nested if statements to do the same task. In this case, if the test Zombie is in front of Mana<br />
is false, it skips the second if statement completely, and she can walk forward. If Mana is in front of the<br />
Zombie, the nested if statement is tested. if Mana is within .25 meters in front of the Zombie, she can go no<br />
closer.<br />
there are three possibilities with the above example:<br />
The Zombie is not in front of Mana<br />
The Zombie is in front of Mana, but at a distance greater than .25 meters<br />
The Zombie is in front of Mana, at a distance of less than or equal to .25 meters.<br />
Let's look at each of these in turn:<br />
The Zombie is not in front of Mana<br />
The second modification to the mana.forward method.<br />
The mana.forward method modified with nested if statements.<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\03\nested-if.html<br />
Page 3 of 5<br />
18/03/2008
Nested IF Statements<br />
The Zombie is not in front of Mana.<br />
The program first looks at the test in the first if statement and evaluates, "Is the Zombie in front of Mana?". As<br />
this is not correct, the result is false. The commands in the else clause of the first if statement are then<br />
executed.<br />
The Zombie is in front of Mana but at a distance greater than .25 meters<br />
The Zombie is in front of Mana.<br />
Once again, the program looks at the first if statement. This time the Zombie is in front of Mana, so the result<br />
is true.<br />
The Zombie is in front of Mana but over 0.25 meters away.<br />
The program then evaluates the second if statement, "Is the the Zombie less than or equal to 0.25 meters<br />
away from Mana?". In this case, the distance is greater than 0.25 meters; the result is false. So the commands<br />
in the second if statement's else clause are executed. Mana is able to move forward.<br />
The Zombie is in front of Mana at a distance of less that or equal to .25 meters.<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\03\nested-if.html<br />
Page 4 of 5<br />
18/03/2008
Nested IF Statements<br />
The Zombie is in front of Mana.<br />
The program evaluates the first if statement. This time the Zombie is in front of Mana, so the result is true.<br />
The Zombie is in front of Mana but less than 0.25 meters away.<br />
The second if is then evaluated; "Is the Zombie in front of Mana, and is the distance less than or equal to .25<br />
meters?". In this case the result is true; the distance is less than .25 meters. The second if statement is<br />
processed, with the action of "do nothing". As a consequence, Mana is not able to move any nearer to the<br />
Zombie.<br />
If we look at our original scenario, we need to add code to get Mana to say, "I see dead people". She must only<br />
say it if the Zombie is in front of her, and the distance between her and the Zombie less than 0.5 metres. The<br />
final Mana.move method then becomes.<br />
The final Mana.move method<br />
Note: the "I see dead people" if statement must also be added to the Mana.turnleft method.<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\03\nested-if.html<br />
Page 5 of 5<br />
Up | Site Map<br />
18/03/2008
Tutorial 3<br />
Introduction to Programming<br />
C ha p ter 3: IF St atements<br />
Tutorial Exercises<br />
The Scenario<br />
Up | Site Map<br />
Mana is a child of slightly spooky appearance, who can move forward (up arrow key), left (left<br />
arrow key) and right (right arrow key). The initial scene contains Mana and a fire-hydrant.<br />
Mana obeys the usual laws of physics, in that she can't walk through objects. The aim is to<br />
allow Mana to walk around this world.<br />
For the purpose of this exercise, Mana has the following functions:<br />
Mana distance to object<br />
Mana distance infront of object<br />
Mana is infront of object<br />
Mana's width<br />
Mana's depth<br />
She has the following methods:<br />
Mana move distance<br />
Mana move towards object<br />
Mana turn distance<br />
The world with Mana and the Fire Hydrant<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\03\tutorial.html<br />
Page 1 of 2<br />
18/03/2008
Tutorial 3<br />
Distance can be a simple amount (e.g. 0.1 metre) or a formula (e.g. a - b , where a and b are<br />
then replaced with numbers, functions or other formulae).<br />
The fire-hydrant has functions and methods of the same type as Mana's (e.g. [fire-hydrant<br />
distance to Object])<br />
The World provides the following functions:<br />
a = b<br />
a > b<br />
a < b<br />
both a and b (meaning test a is true and test b is true)<br />
either a or b, or both<br />
not a<br />
The dummy items a and b are then replaced by functions or formulae. (e.g. [ (4 - 2) < Mana<br />
distance to fire-hydrant ] ). You can create events saying what method to run when a key is<br />
pressed (e.g. [ when space is typed do method ] )<br />
Questions<br />
You are encouraged to discuss these questions and share useful links you've found with others<br />
in the discussion forum.<br />
The first task is to get Mana to move. We need to get Mana to respond the the three arrow<br />
keys.<br />
1. How can this be accomplished?<br />
2. Do we need to create any extra methods for Mana's movements?<br />
Problem: Mana will happily walk right through the fire-hydrant. Note that she can only walk<br />
through the fire-hydrant by moving forward (not by moving sideways etc as the only action<br />
keys are move forward, and turn). Think about what information you need to prevent walking<br />
through the fire-hydrant.<br />
3. What information is required to stop Mana from walking through other objects?<br />
4. What functions will give us the required information?<br />
5. Do we need to use an if statement with this information?<br />
6. If we do need an if statement, suggest how this should be implemented.<br />
Once you feel there has been sufficient discussion for you to attempt to code this problem,<br />
please go ahead and write the solution using Alice.<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\03\tutorial.html<br />
Page 2 of 2<br />
Up | Site Map<br />
18/03/2008
Practical 3<br />
Introduction to Programming<br />
Chapter 3: IF Statements<br />
Practical E x ercise s<br />
Lets have another look at our cow and snake scenario; it got a bit scary for the cow last week so we'll change the<br />
scenario a bit, and we'll also add some user interaction.<br />
The Scenario<br />
Up | Site Map<br />
One day a cow was out walking in the field, where there is also a snake. (The snake will slither away when the user<br />
presses the space key, or if the cow jumps up and down.) The cow stops, and swishes its tail a few times. the cow then<br />
looks down; if it sees the snake, the cow says, "Eek!! A snake!", and jumps up and down to frighten away the snake.<br />
The snake then slithers away from the cow. If the cow doesn't see the snake, the cow says, "There is no snake here."<br />
and does not need to frighten away the snake.<br />
What are the objects in our scenario?<br />
The Cow and the Snake<br />
What is the interaction required?<br />
When the user presses the space bar, the snake slithers away.<br />
What are the actions? (Storyboard)<br />
Cow walks towards Snake<br />
Cow stops<br />
Cow waves tail<br />
Cow looks down<br />
if the Cow sees a Snake<br />
else<br />
Cow says, "Eek!! A snake!"<br />
Cow jumps up and down<br />
Snake slithers away<br />
Cow says, "I see no snake here."<br />
Page 1 of 5<br />
We already have most of this completed from last weeks' work. Open up the interaction demo from last week (don't<br />
forget to save this week's work with a different name!) We'll first change the interaction required. change the<br />
cow.lowerHead to snake.slide by clicking on the arrow at the end of the event.<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\03\practical.html<br />
18/03/2008
Practical 3<br />
Change cow.lowerHead to snake.slide<br />
Page 2 of 5<br />
We now need to add back our cow.lowerHead to under the cow.tailSwish method. Next select the if/else statement from<br />
the bottom of the Editor area, and drop this below cow.lowerHead. For now, select true; we'll change the test to what is<br />
needed later. The world object has the logic functions that we require. Click on world in the object tree, and functions in<br />
the details area.<br />
We need to test if the cow can see the snake. For this, we'll assume that if the distance from the cow to the snake is<br />
greater than 2 metres, the cow cannot see the snake. In the math functions, we need a < b; select this function and<br />
drop it over the true section of the if statement. For now, just make it if 2 < 2. Now we need to get our distance<br />
between the cow and the snake, but we need the end of the snake that's closest to the cow. Now what do we need to<br />
do is: if the distance is less than 2 metres, move the required methods into the top box in the if statement.<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\03\practical.html<br />
18/03/2008
Practical 3<br />
We can now place the actions that the cow and snake do if the result of the test is true (if the cow sees a snake):<br />
Cow says, "Eek!! A snake!";<br />
Cow jumps up and down; and<br />
Snake slithers away.<br />
These get placed in the box just below the test section.<br />
The if statement with the test included.<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\03\practical.html<br />
Page 3 of 5<br />
18/03/2008
Practical 3<br />
The actions to carry out if the if test is true.<br />
Drag and drop the second cow say in the lower box of the if statement. Change what the cow says to what is required.<br />
Adding the cow say text<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\03\practical.html<br />
Page 4 of 5<br />
18/03/2008
Practical 3<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://D:\_Contribute_Material\cpt120\chapter\03\practical.html<br />
Page 5 of 5<br />
Up | Site Map<br />
18/03/2008
Chapter 4: Loops<br />
Introduction to Programming<br />
Chapter 4: Loops<br />
At the completion of this weeks study students should.<br />
Know how to repeat actions a specified number of times<br />
Know how to use if statements within a loop<br />
Understand infinite loops<br />
Co urse Materials<br />
Online Course Material<br />
Please select a subtopic to view its contents.<br />
Introduction to Loops<br />
Tutorial and Practical Exercises<br />
Tutorial Exercises<br />
Practical Exercises<br />
Additional Materials<br />
Textbook: "Learning to Program with Alice", W. Dann et al., Pearson Prentice Hall.<br />
Chapter 7, pp183-194<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://I:\20080325\cpt120\chapter\04\index.html<br />
Page 1 of 1<br />
Up | Site Map<br />
Up | Site Map<br />
25/03/2008
Introduction to Loops<br />
Introduction to Programming<br />
Chapter 4: Lo ops<br />
I ntroduction to L oops<br />
Basic Scones (From My Mum's notes)<br />
Ingredients<br />
3 cups self-raising flour<br />
80g butter, cubed<br />
1 to 1 1/4 cups milk<br />
Method<br />
Preheat oven to 200°C. Lightly dust a flat baking tray with plain flour.<br />
Sift the self-raising flour into a bowl.<br />
Using your fingertips, rub the butter into the self-raising flour until the mixture resembles breadcrumbs.<br />
Make a well in the center of this mixture. Add 1 cup of milk.<br />
Mix with a fork until the mixture forms a soft dough, add more milk if required.<br />
Turn onto a lightly floured surface. Knead gently until the dough is smooth.<br />
Push the dough into a 2cm-thick round.<br />
Using a 5cm round cutter, cut out as many scones as you can.<br />
Press the dough together and cut out the remaining scones.<br />
Place scones onto prepared baking tray, 1cm apart. Sprinkle tops with a little plain flour.<br />
Bake for 20 to 25 minutes or until golden and well risen.<br />
Transfer to a wire rack.<br />
Serve warm with jam and cream.<br />
Up | Site Map<br />
You could be forgiven for thinking that this course on programming has suddenly turned to cookery, but have another<br />
look; many times in this recipe we are repeating the same actions.<br />
For example, where we need to "mix with a fork until the mixture forms a soft dough", or "knead gently until smooth".<br />
In these steps, we are repeating something until a condition is met. In programming, this is called looping. Loops are<br />
used when we need to repeat one or many actions a number of times. The first example could be written as:<br />
loop:<br />
mix with a fork<br />
while the mixture has not formed a soft dough.<br />
In this example the loop is started and we start to mix the mixture with a fork. After a while, we then test the mixture<br />
and see if it has formed into a soft dough. If this test is true (it is not a soft dough), we then go back to the start of the<br />
loop. In this case seeing that we have only one instruction "inside the loop", we continue to mix with a fork until the<br />
mixture has formed a soft dough.<br />
As with our previous topic on if statements, we use loops countless times in our everyday lives. We go to a petrol<br />
station to fill up the car with petrol, and we add petrol to the tank while it is not full. Likewise with programming, if<br />
statements and loops are the most common program control structures.<br />
Let's Have a Look at Loops in Alice<br />
Page 1 of 6<br />
In the Wild West folder is a Sheriff; let's make him dance 5 times. We could write a method to make him raise and<br />
lower his left leg, the method for the right leg would be similar.<br />
<strong>file</strong>://I:\20080325\cpt120\chapter\04\loops-intro.html<br />
25/03/2008
Introduction to Loops<br />
The method to make him step with his left leg<br />
Now we need to make him do this five times. We could place the stepLeft and stepRight methods in a do in order box<br />
and then repeat this five times.<br />
The stepLeft - StepRight methods repeated five times<br />
What would it be like if we needed to make the Sheriff dance fifty times, or even five hundred times? The program<br />
would become huge and unmanageable.<br />
There is a type of loop that we can use to accomplish this, for cases such as these where we know the number of times<br />
an action needs to be repeated. In Alice this is referred to as a counted loop. Each time through the loop, a counter is<br />
incremented until the count matches the required number of repetitions.<br />
In many programming languages this type of loop is called a for loop. If we have a look at the complicated version, we<br />
can see that there is a counter called index that starts from zero. the counter gets incremented (in this case by 1) each<br />
time the loop is executed. The final value of the counter will then be up to but not including 5. As a result, the counter<br />
will start at 0 and end at 4, a total of five times through the loop.<br />
The program flow in this type of loop is:<br />
The various sections of a counted loop<br />
firstly the counter is initialized to the start value;<br />
then a test is made to see if the counter is equal to the 'stop before' value<br />
If this test is false, the code within the loop is executed. The counter is then<br />
incremented and the test is done again.<br />
Once the result of the test is true the loop ends.<br />
<strong>file</strong>://I:\20080325\cpt120\chapter\04\loops-intro.html<br />
Page 2 of 6<br />
25/03/2008
Introduction to Loops<br />
Note: If the test returns true at the first iteration of the loop, no part of the loop's insides are<br />
executed.<br />
Loops Containing IF Sta t ements<br />
The two views of the Sheriff loop<br />
Page 3 of 6<br />
The Scenario: One day a cow was out walking in the field. Suddenly it sees a snake in the grass and waves its tail in<br />
fright. The cow then says, "Eek!! A snake!", and then walks around the snake at a distance of 2 meters.<br />
The actions in this scenario are more complicated than the previous cow and snake examples. We cannot use the cow<br />
walktowards method, as we actually have to walk past the snake.<br />
We must first get the cow walking towards the snake. After this, we must use a loop to get the cow walking a short<br />
distance, and then check if the distance between the snake and the cow is within the required range. If this is the case,<br />
the outer loop is interrupted and the actions within the if statement are executed.<br />
<strong>file</strong>://I:\20080325\cpt120\chapter\04\loops-intro.html<br />
25/03/2008
Introduction to Loops<br />
Using an if statement within the loop to interrupt the program flow<br />
Note: I have also used another loop within the outer loop. Once the actions within the if statement have completed, the<br />
program flow returns to the first loop.<br />
We could further modify the previous method by using a distanceTo function to enable our "smart cow" to know the<br />
number of times it must walk towards the snake. The program would then use this value in the loop, and allow the cow<br />
to walk that many times towards the snake.<br />
The distanceTo function used to get the distance between the cow and the snake<br />
Page 4 of 6<br />
As we have seen in the complicated version, this type of loop uses a counter to count between the start value and the<br />
end value. We can view this counter as the program runs, by placing a print statement (available below the editor area)<br />
within the loop:<br />
<strong>file</strong>://I:\20080325\cpt120\chapter\04\loops-intro.html<br />
25/03/2008
Introduction to Loops<br />
Infinite Loops<br />
A print method used within a loop<br />
In most cases, we want a loop to eventually finish; a loop that never ends would be a problem. That being said, there<br />
may be times where an infinite loop can be used to our advantage.<br />
Take the example of creating a continually busy highway: we could have a car move along the highway. Once it's at the<br />
end, make it invisible and move it back to the starting position. Make it visible again, and move it along the highway.<br />
If we placed these actions inside an infinite loop, it would appear as if many cars were traveling along the highway,<br />
even if each car looks the same as the one before.<br />
Using an infinite loop to simulate a busy highway<br />
<strong>file</strong>://I:\20080325\cpt120\chapter\04\loops-intro.html<br />
Page 5 of 6<br />
Up | Site Map<br />
25/03/2008
Introduction to Loops<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://I:\20080325\cpt120\chapter\04\loops-intro.html<br />
Page 6 of 6<br />
25/03/2008
Tutorial 4<br />
Introduction to Programming<br />
Chapter 4: L o o ps<br />
Tutor i al E xercises<br />
Aim: To investigate loops.<br />
Questions<br />
You are encouraged to discuss these questions and share useful links you've found with others in the discussion<br />
forum<br />
Up | Site Map<br />
1. Write a loop to make a ballerina perform a jumping pirouette (she jumps a metre high in the air, and makes a<br />
complete turn while in the air) 5 times.<br />
2. Write a loop to make a penguin walk in a (equilateral) triangular path. Then change it to walk in a hexagonal path.<br />
3. Sometimes the meaning of what a programmer wrote isn't what s/he intended. We then say the program has a<br />
logic error. Consider the following loop - if the programmer intended the loop to run 3 times, does it have a logic<br />
error? How many times will the loop run?<br />
Is there a logic error in this loop?<br />
4. Consider the following loop. Describe what the Sheriff will do.<br />
What will the sheriff do in this example?<br />
5. Design a program using loops where two skaters perform a routine. They start at diagonal corners of a virtual<br />
square and skate around the square. Use as few move commands as you can.<br />
<strong>file</strong>://I:\20080325\cpt120\chapter\04\tutorial.html<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
Page 1 of 1<br />
Up | Site Map<br />
25/03/2008
Practical 4<br />
Introduction to Programming<br />
Chapter 4: Loops<br />
Practical Exercises<br />
The Scenario<br />
Up | Site Map<br />
Six penguins are practicing a new dance routine. They start lined up in two rows of three;<br />
each penguin is two meters away from the penguin alongside or in front/behind of them. The<br />
penguins perform a synchronized walk, moving in a square (the two rows walking in different<br />
directions). Their dance lasts for five complete squares. There is also an igloo, which has a<br />
dance sign that constantly flashes.<br />
Let's stop and think about this program before rushing in to writing the code. Firstly we need<br />
to discover what objects are needed for the story board.<br />
What objects in our scenario ?<br />
Six penguins<br />
An Igloo<br />
A Dance sign<br />
Download the initial PenguinDance <strong>file</strong> here penguinDance.a2w<br />
The initial penguinDance screen<br />
Page 1 of 4<br />
We are told in the scenario that the Igloo has a sign that flashes continuously. We have used<br />
<strong>file</strong>://I:\20080325\cpt120\chapter\04\practical.html<br />
25/03/2008
Practical 4<br />
an infinite loop and the visibility property of an object previously, with the busy highway<br />
example. This is a similar situation here, in that we need to flash the dance sign. To do this,<br />
we need to make its visibility property false. This effectively turns the sign off; making it<br />
visible turns the sign back on. This needs to be done continuously - a good use for an infinite<br />
loop. The story board up to this point is then:<br />
// get the sign to flash continuously<br />
Loop infinity times<br />
dance set isShowing to false<br />
dance set isShowing to true<br />
Now we can work on getting the penguins to do their dance. We are told that the penguins<br />
move in a square and that the two rows move in different directions. Let's get our penguins to<br />
do one square first. At each side of the square, all of the penguins walk forward one metre.<br />
One row of three penguins will then turn left, and the other three will turn right. We then need<br />
to get our penguins to do this four times to complete the "square dance". Our storyboard for<br />
one square dance is:<br />
// get the penguins to do their dance<br />
// Dance one square<br />
Loop 4 times<br />
Do together<br />
// get the penguins to walk a side of the square<br />
penguin walk 1 meter forward<br />
penguin2 walk 1 meter forward<br />
penguin3 walk 1 meter forward<br />
penguin4 walk 1 meter forward<br />
penguin5 walk 1 meter forward<br />
penguin6 walk 1 meter forward<br />
Do together<br />
// get the penguins to turn left or right<br />
penguin turn left .25 revolutions<br />
penguin2 turn left .25 revolutions<br />
penguin3 turn left .25 revolutions<br />
penguin4 turn right .25 revolutions<br />
penguin5 turn right .25 revolutions<br />
penguin6 turn right .25 revolutions<br />
We now only need to combine these two parts of the storyboard using a do together. We also<br />
need to get the penguins to complete the full dance, by placing our 'square dance' inside<br />
another loop that is set to repeat five times. The final storyboard is then:<br />
Do Together<br />
// get the sign to flash continuously<br />
Loop infinity times<br />
dance set isShowing to false<br />
dance set isShowing to true<br />
// get the penguins to do their dance<br />
Loop 5 times<br />
// Dance one square<br />
<strong>file</strong>://I:\20080325\cpt120\chapter\04\practical.html<br />
Page 2 of 4<br />
25/03/2008
Practical 4<br />
Loop 4 times<br />
Do together<br />
// get the penguins to walk a side of the square<br />
penguin walk 1 meter forward<br />
penguin2 walk 1 meter forward<br />
penguin3 walk 1 meter forward<br />
penguin4 walk 1 meter forward<br />
penguin5 walk 1 meter forward<br />
penguin6 walk 1 meter forward<br />
Do together<br />
// get the penguins to turn left or right<br />
penguin turn left .25 revolutions<br />
penguin2 turn left .25 revolutions<br />
penguin3 turn left .25 revolutions<br />
penguin4 turn right .25 revolutions<br />
penguin5 turn right .25 revolutions<br />
penguin6 turn right .25 revolutions<br />
Page 3 of 4<br />
Remember that when you code this scenario up in Alice, there is a method for each penguin<br />
called Walking. please use this method with a length of 1. Remember also that each penguin<br />
is a separate object, so you will need to make each penguin walk and turn individually, as<br />
shown in the storyboard.<br />
<strong>file</strong>://I:\20080325\cpt120\chapter\04\practical.html<br />
25/03/2008
Practical 4<br />
The final penguin dance program<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://I:\20080325\cpt120\chapter\04\practical.html<br />
Page 4 of 4<br />
Up | Site Map<br />
25/03/2008
Chapter 5: While Loops<br />
Introduction to Programming<br />
Chapter 5: While Loops<br />
At the completion of this weeks study students should.<br />
Understand the difference between for loops and while loops.<br />
Understand the use of functions in loops<br />
Understand that While loops continue only while the test is TRUE<br />
Understand the difference between if statements and while loops<br />
Understand the danger of creating infinite loops<br />
Co urse Materials<br />
Online Course Material<br />
Please select a subtopic to view its contents.<br />
While Loops<br />
Nested Loops<br />
Tutorial and Practical Exercises<br />
Tutorial Exercises<br />
Practical Exercises<br />
Additional Materials<br />
Reading References<br />
While Loops | Up<br />
Prev | 1 2 t p | Next<br />
Textbook: "Learning to Program with Alice", W. Dann et al., Pearson Prentice Hall<br />
Chapter 7, pp183-194<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\05\index.html<br />
Page 1 of 1<br />
Prev | Up | Next<br />
31/03/2008
While Loops<br />
Introduction to Programming<br />
Chapter 5: While L oops<br />
W hile L oops<br />
While Loops | Up<br />
Prev | 1 2 t p | Next<br />
Last week we looked at counted loops (aka for loops). These are loops that repeat a specific number of times. This<br />
week, looks at another type of loop called while loops. In this type of loop, we repeat an action or series of actions for<br />
however long a particular test expression is true. Once the test expression is false, the loop ends and the program<br />
continues with its next instruction.<br />
Think back to the scone recipe from last week, there was a line that said, "mix with a fork until the mixture forms a soft<br />
dough". This line could have also be written as:<br />
While the mixture has not formed a soft dough<br />
beat the mixture with a fork.<br />
In Alice, there are times when we need to repeat some action while a condition is true. Let's go back to the cow and<br />
snake scenario from last week: in that example, we used an if statement to test if the cow was getting close enough to<br />
the snake.<br />
Using an If statement to test the distance between the cow and the snake<br />
We could have also used a while loop to move the cow towards the snake. In this case, "Snake distance in front of cow<br />
> 0.5" would be the condition that must be kept true while the cow is walking towards the snake. At each iteration of<br />
the while loop, it will perform the distance check and move the cow 0.25 metres closer if necessary. This process of<br />
checking the condition and issuing the instruction will repeat for as long as the condition is true. When the cow is finally<br />
close enough, the while condition will become false, and the loop will end.<br />
The initial scenario, changed to use a while loop to test the distance between the cow and snake<br />
There can also be situations where the instructions inside a loop are not executed. If the initial scene had the cow<br />
standing on top of the snake, or the cow in front of the snake, the test "Snake distance in front of cow > .5" would be<br />
false; in these cases the snake is not in front of the cow. In this instance, the instructions inside the loop would be<br />
skipped over.<br />
Confusion Between IF Statements and While Loops<br />
Page 1 of 5<br />
If you consider the previous two examples with the cow and snake, both the IF statement and the While loop use a test<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\05\while-loops.html<br />
31/03/2008
While Loops<br />
to see if commands should be executed. The major difference is that an IF statement will only test once; the While loop<br />
repeats the test and the commands within the loop until the test fails.<br />
While Loop Example<br />
Scenario<br />
IF Statement: "move cow" can only be done (at most) once While Loop: "move cow" might be done many times<br />
Mana is able to walk freely around her world. Also living in the in the same world is a Zombie that will try and catch her,<br />
if she gets too close (less than 2 meters in front). Once Mana is within range of the Zombie, Mana will be chased by the<br />
Zombie until she is caught.<br />
In the above methods, an if statement is used to first test if Mana is within range of the Zombie. Once the test 'Mana is<br />
in front of zombie and mana distance in front of zombie < 2' is true, the program flow switches to the zombie.attack<br />
method. If the test in zombie.forward is false (Mana is not within range of the Zombie), Mana is free to move forward.<br />
Once program flow has changed to zombie.attack, a test is continually made (in a loop) to make sure that the distance<br />
between Mana and the Zombie is still greater than 0.1 meters. Once this test is false, i.e. the distance between Mana<br />
and the Zombie is < .25 metres, the loop ends. The next instruction after the loop is executed" 'zombie say "gotcha"'.<br />
We can see from these two functions that in zombie.forward, the test and the statements within the if statement are<br />
executed once only. In contrast, in the zombie.attack method, the actions within the loop are repeated while the loop<br />
test is true.<br />
Accidental Infinite Loops<br />
The zombie.forward and zombie.attack methods from the above scenario<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\05\while-loops.html<br />
Page 2 of 5<br />
31/03/2008
While Loops<br />
Let's have a look at a few Alice examples that do not go according to plan. When using while loops it is important to<br />
actually have a situation where the test can be false.<br />
The Scenario<br />
Mana is facing a crate, she moves forward while she is greater than or equal to 0.25 metres away from the crate<br />
Consider what would happen if Mana was metres 2.1 meters from the crate:<br />
Mana is 2.1 metre away from the crate. The loop test is true, and she moves forward 1 metre<br />
Mana is 1.1 metre away from the crate. The loop test is true, and she moves forward 1 metre<br />
Mana is 0.1 metre away from the crate. The loop test is false, and the loop ends.<br />
However, consider what would happen if Mana was initially 1.5 meters from the crate:<br />
Mana is 1.5 metre away from the crate. The loop test is true, and she moves forward 1 metre<br />
Mana is 0.5 metre away from the crate. The loop test is true, and she moves forward 1 metre<br />
(Mana walks through the crate. The crate is now .5 metres behind her, which is greater than 0.25 metres)<br />
Mana is 0.5 metre away from the crate. The loop test is true, and she moves forward 1 metre<br />
Mana is 1.5 metre away from the crate. The loop test is tru, and she moves forward 1 metre<br />
Mana is 2.5 metre away from the crate. The loop test is true, and she moves forward 1 metre<br />
and so on. The loop will never end.<br />
Another Scenario<br />
Mana is being chased by a Zombie, but she is able to outrun any Zombie. For every 0.5 metres the Zombie moves,<br />
Mana moves 1 metre. If the Zombie gets to within 0.25 meters of Mana, she will be caught.<br />
In this case the distance between Mana and the Zombie can never get to within .25 meters. For each move the distance<br />
between them is increasing by .5 meters. If we take the start distance as .5 meters<br />
Mana is 0.5 metres away from the Zombie. The loop test is true. She moves forward 1 metre. The zombie moves<br />
0.5 metres.<br />
Mana is 1.0 metres away from the Zombie. The loop test is true. She moves forward 1 metre. The zombie moves<br />
0.5 metres.<br />
Mana is 1.5 metres away from the Zombie. The loop test is true. She moves forward 1 metre. The zombie moves<br />
0.5 metres.<br />
Mana is 2.0 metres away from the Zombie. The loop test is true. She moves forward 1 metre. The zombie moves<br />
0.5 metres.<br />
Mana is 2.5 metres away from the Zombie. The loop test is true. She moves forward 1 metre. The zombie moves<br />
0.5 metres.<br />
From this behaviour, we can see that the distance between them will never get to less than 0.25 metres, and the loop<br />
will never end.<br />
Using an Object's Properties in a Loop<br />
Mana moves forward while she is greater than .25 meters from the crate<br />
An accidental infinite loop<br />
Page 3 of 5<br />
We can also use an object's properties in the loop test. In this instance the isShowing property of the fan's off bottom is<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\05\while-loops.html<br />
31/03/2008
While Loops<br />
tested. This is to make it such that while the off button is showing, the blades will turn. Once the user clicks the off<br />
button, the off button is made invisible and the loop test returns false. The loop then ends, and the fan's blades stop<br />
turning.<br />
Ra ndomness<br />
The ability to use randomness in our programs can, at times, be used to good effect. In the world object, we have<br />
provided for us two functions. One called choose true, which returns true a defined percentage of times. The other<br />
function, random number, allows us to generate a number within a upper and lower range.<br />
Scenario<br />
Testing the properties of an object in a loop<br />
A Cow and (possibly) a Snake are in a field. 50% of the time the program is run, the snake is not there. If the Snake is<br />
in the field, the Cow walks towards it, stops just before it reaches the Snake, looks down and says, "Eek! A snake!". If<br />
the Snake is not there the Cow just keeps walking.<br />
To obtain the 50% randomness, we'll use the choose true method, and make the visibility property of the snake true or<br />
false depending on the returned value. The resultant code would look like:<br />
Using the 'choose true' method to make the snake visible or invisible<br />
Page 4 of 5<br />
Let's change the scenario a bit now. If the snake is not there, the cow turns a random revolution (and either left or<br />
right), and then walks off. The random value can be obtained from the random number function. By setting the range<br />
of this function from -0.25 to 0.25 revolutions, a turn left method can then be used to obtain either a left or a right turn<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\05\while-loops.html<br />
31/03/2008
While Loops<br />
for the cow.<br />
Using a 'random number' function to generate left or right turn for the cow<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\05\while-loops.html<br />
Page 5 of 5<br />
Prev | Up | Next<br />
31/03/2008
Nested Loops<br />
Introduction to Programming<br />
Chapter 5: While Loops<br />
Neste d Loops<br />
Nested Loops | Up<br />
Prev | 1 2 t p | Next<br />
In last weeks <strong>material</strong>, you were introduced to a programming structure known as looping. With this in mind,<br />
let's have another look at the Dancing Sheriff. You will recall that we wrote two methods, called stepLeft and<br />
stepRight. We then used these in a loop to get the sheriff to dance five times:<br />
The next step in this scenario: The Sheriff has learnt the next part to his dance routine; this time he does two<br />
steps with his left leg, then two steps with his right leg, and repeats this set of actions five times.<br />
We could write a loop that repeats the step routine the required number of times:<br />
Nested Loops<br />
The Sheriff Dance loop from last weeks <strong>material</strong><br />
The stepLeft, stepRight methods repeated in a loop<br />
Page 1 of 4<br />
Another method we could use to solve this problem, called nested loops, is to place one or more loops inside<br />
another loop. With this type of looping, for each time through the outer loop, the inner loop(s) will repeat. In the<br />
Sheriff Dance we have already got a loop that repeats the Sheriff stepping five times.<br />
Within this outer loop two inner loops are required, each repeating two times. In one inner loop the stepLeft<br />
method is listed, the other contains the stepRight method. In this way, each stepLeft/stepRight method is<br />
repeated two times and these two 'inner loops' are then repeated five times in the 'outer loop'.<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\05\nested-loops.html<br />
31/03/2008
Nested Loops<br />
Investigating a Nested Loop<br />
In this nested loop:<br />
the outer loop will repeat 3 times (the value of index will start at 0 and go to 2)<br />
Each time the outer loop repeats, the inner loop will repeat two times (the value of index_#2 will start at 0<br />
and go to 1).<br />
This table provides an indication of the values in each of the loop indexes, at each step.<br />
Deeply Nested Loops<br />
Using nested loops to get the sheriff to dance<br />
A nested loop<br />
index index_#2<br />
Another scenario: This time the Sheriff has learnt another part of the dance routine. He does the previous<br />
routine (stepLeft, stepLeft, stepRight, stepRight) and repeats this four times; but now, after each repetition, he<br />
makes a quarter turn to the left.<br />
All we need to do this time, is add the add the method to turn the Sheriff after the loop.<br />
0<br />
. 0<br />
. 1<br />
1<br />
. 0<br />
. 1<br />
2<br />
. 0<br />
. 1<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\05\nested-loops.html<br />
Page 2 of 4<br />
31/03/2008
Nested Loops<br />
We could make the Sheriff repeat this dance a number of times, by adding yet another loop.<br />
Analysing a Nested Loop<br />
The Sheriff makes a quarter turn after each loop<br />
Repeating the Sheriff's dance by adding another outer loop<br />
We can test this for ourselves, with a loop structured like so:<br />
Nested loops to a depth of three<br />
If we examine the index variables of this loop at each stage, the table of values looks like:<br />
index index_#2 index_#3<br />
0<br />
. 0<br />
. . 0<br />
. . 1<br />
. 1<br />
. . 0<br />
. . 1<br />
1<br />
. 0<br />
. . 0<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\05\nested-loops.html<br />
Page 3 of 4<br />
31/03/2008
Nested Loops<br />
In this nested loop:<br />
the outer loop will repeat 2 times (the value of index will start at 0 and go to 1).<br />
Each time through the outer loop, the middle loop will repeat two times (the value of index_#2 will start at<br />
0 and go to 1).<br />
Each time through the middle loop, the inner loop will repeat two times (The value of index_#3 will start at<br />
0 and go to 1).<br />
. . 1<br />
. 1<br />
. . 0<br />
. . 1<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\05\nested-loops.html<br />
Page 4 of 4<br />
Prev | Up | Next<br />
31/03/2008
Tutorial 5<br />
Introduction to Programming<br />
Chapter 5: While Loops<br />
T utorial Exercises<br />
Aim: To investigate while loops, nested loops and method parameters.<br />
Questions<br />
Tutorial Exercises | Up<br />
Prev | 1 2 t p | Next<br />
You are encouraged to discuss these questions and share useful links you've found with others in the<br />
discussion forum.<br />
Q1. What is going to be the result of running the following while loop? What other loop is this<br />
equivalent to this in behaviour?<br />
Q2. Consider the following loop. What will the value of index be each time through the loop? The<br />
loop will operate 4 times. The first time, index will be 0. The second time, index will be 1, and so on.<br />
What path will the penguin take?<br />
Q3. There is an outer loop (4 times) and an inner loop (3 times). It might help to think of the loops<br />
as wheels. We have a wheel inside a wheel. For every 1 turn of the outer wheel, the inner wheel will<br />
turn 3 times.<br />
The expanded version of the loops are shown below:<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\05\tutorial.html<br />
Page 1 of 2<br />
31/03/2008
Tutorial 5<br />
Keep track of index and index_2. What path the penguin will take this time?<br />
Q4. Consider the following loops. What will the penguin do?<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\05\tutorial.html<br />
Page 2 of 2<br />
Prev | Up | Next<br />
31/03/2008
Practicals 5<br />
Introduction to Programming<br />
Chapter 5: While Loops<br />
Practical Exercises<br />
Practical Exercises | Up<br />
Prev | 1 2 t p | Next<br />
Implement the following scenarios (that include loops and the World.random function) in your<br />
program:<br />
Q1 Scenario: A penguin is rapidly running in the shape of a square, ten times. This makes<br />
the penguin very dizzy. It abruptly staggers 0.25 meters by a random degree to the left or<br />
right five times, then falls face first into the snow.<br />
Q2 Scenario: Using the <strong>file</strong> ComboLock.a2w create four class methods - leftOne, rightOne,<br />
leftRev and RightRev - that turn the combination lock dial one number left, one number right,<br />
one revoultion left and one revolution right, respectively. Then create a method called open<br />
that opens the lock, and another, close, that closes the lock.<br />
Hint: one position on the dial is 1/40th of a revoultion.<br />
Finally, use loops and the above methods to implement a combination of 10 left, 41 right, 16<br />
left, then open the lock. Wait 5 seconds and close it again.<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\05\practical.html<br />
Page 1 of 1<br />
Prev | Up | Next<br />
31/03/2008
Chapter 6: Method Parameters and Modelling<br />
Introduction to Programming<br />
Chapter 6: Method Parameters and Model l ing<br />
At the completion of this weeks study, students will have:<br />
Knowledge of what method parameters are, and what they may contain<br />
The ability to create methods with input parameters<br />
An awareness of what generic methods are, and how to create them.<br />
Knowledge of how to use modelling to design a program<br />
Co urse Materials<br />
Online Course Material<br />
Please select a subtopic to view its contents.<br />
Method Parameters<br />
Modelling<br />
Tutorial and Practical Exercises<br />
Practical Exercises<br />
Additional Materials<br />
Reading References<br />
Method Parameters and Modelling | Up<br />
Prev | 1 2 p | Next<br />
Textbook: "Learning to Program with Alice", W. Dann et al., Pearson Prentice Hall<br />
Chapter 4, pp83-92<br />
Chapter 5, pp125-134<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\06\index.html<br />
Page 1 of 1<br />
Prev | Up | Next<br />
31/03/2008
Chapter 6: Method Parameters<br />
Introduction to Programming<br />
Chapter 6: Method Parameters a nd Mode lling<br />
Me t h od Parameters<br />
Method Parameters | Up<br />
Prev | 1 2 p | Next<br />
Up to now, you have used many methods to do various actions. With the Cow and Snake scenarios<br />
you have used move, turn and other methods in your programs. These methods allow us to pass<br />
information (or objects) to them.<br />
Input parameters tell a method information such as (for a move method) which object to move, how<br />
far to move it, or what percentage of a circle to turn an object and in which direction. The move<br />
object has a number of parameters passed to it, including the object to move, the direction to move<br />
and how far to move.<br />
With each of these parameters, a different value or object can be specified. This allows us to carry<br />
out different actions on the same object, or use a different object with the same method. In the case<br />
of the move method, we can tell to move the snake one time, and at another time use it for another<br />
object.<br />
When we create a method, it may be necessary to pass various pieces of information to it. We can do<br />
this by defining the required method parameters, along with the required type of each parameter. For<br />
instance, if we need to pass in an object, the parameter must be defined as an object type. Likewise,<br />
if we are passing in a number, the corresponding parameter must be befined as a numeric type.<br />
Defining Method Parameters<br />
The input parameters to a move method<br />
With the following scenario, we are able to define method parameters that allow the method to be<br />
used with any object.<br />
A Zombie is chasing the Mad Scientist across a field; in the same field is a poor cow. The Zombie<br />
wants to chase everyone and everything from "his" field.<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\06\method-parameters.html<br />
Page 1 of 5<br />
31/03/2008
Chapter 6: Method Parameters<br />
To accomplish this task in the way we know so far, we would need two methods,<br />
zombie.ChaseScientist, and zombie.ChaseCow. The storyboards for these methods might be:<br />
zombie.ChaseScientist<br />
Zombie turn to face Scientist<br />
while Zombie distance to Scientist > 1 meter<br />
do in order:<br />
zombie.ChaseCow<br />
Zombie move forward 1 meter<br />
Zombie says, "Get out of my field!!"<br />
Zombie turn to face Cow<br />
while Zombie distance to Cow > 1 meter<br />
do in order:<br />
Zombie move forward 1 meter<br />
Zombie says, "Get out of my field!!"<br />
In the two storyboards, the only difference is the object that the Zombie is chasing. If we look back<br />
to the beginning of this week's <strong>material</strong>, we saw that parameters can enable us to pass information<br />
into a method. In the move method, we have seen that the first parameter of this method is the<br />
object we wish to move. Instead of creating two methods [ChaseCow and ChaseScientist], we can<br />
create a single method, where we can pass the object to chase as a parameter. The storyboard might<br />
now look like:<br />
zombie.chaseSomething<br />
Parameter: Victim<br />
Zombie turn to face Victim<br />
The Zombie, with "his" world<br />
while Zombie distance to Victim > 1 meter<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\06\method-parameters.html<br />
Page 2 of 5<br />
31/03/2008
Chapter 6: Method Parameters<br />
do in order<br />
Zombie move forward 1 meter<br />
Zombie says, "Get out of my field!!"<br />
To use a method using parameters, first create a method as you have done previously in other<br />
scenarios. Because it is the Zombie who is doing the chasing, the new method will need to be created<br />
in the Zombie's method window. In the top right corner of the new method is a create new parameter<br />
button. Click on this button; you be will then asked for what type of parameter you wish to pass into<br />
the method, and a name for the parameter.<br />
Click on 'create a new parameter' and select object from the menu<br />
For this method, we need to pass in an object (the one who is to be chased). Select object type in the<br />
Create New Parameter window. Once you have done this, each time you include a method (e.g. turn<br />
to face), the name of the parameter you have previously defined is available for you to select.<br />
The new parameter is available for you to select<br />
Page 3 of 5<br />
Instead of selecting either the Professor or the Cow in the turn to face and distance to methods, this<br />
time we should select the input parameter we have previously defined (Victim) from the list of<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\06\method-parameters.html<br />
31/03/2008
Chapter 6: Method Parameters<br />
objects. Once we have included all the steps from the zombie.ChaseSomething storyboard, The final,<br />
generic, ChaseSomething method is below:<br />
In our previous scenario it was always the Zombie that was doing the chasing, and the distance<br />
moved and what they said was always the same. To make the ChaseSomething method truly generic<br />
we can add more parameters to be able to change who is doing the chasing, how far they move and<br />
what they say. In this case, we would need to include three more parameters:<br />
Who is chasing? (this is an object)<br />
How far to move? (this is a number)<br />
What do they say? (this is a string)<br />
With this new generic method we do not have a specific object that is doing the scenario, we must<br />
include it in the world's method list. After adding the three parameters, the new scenario for our<br />
generic ChaseSomething method is then:<br />
world.ChaseSomething<br />
Parameters: WhoIsChasing, Victim, HowFar, WhatIsSaid<br />
WhoIsChasing turn to face Victim<br />
while whoIsChasing distance to Victim > 1 meter<br />
do in order:<br />
The generic chaseSomething method<br />
WhoIsChasing move forward HowFar<br />
WhoIsChasing says WhatIsSaid<br />
Page 4 of 5<br />
We need to add the three extra parameters and change the existing ChaseSomething method to<br />
include them. Our final 'generic' ChaseSomething is shown below. When we use this new method the<br />
program will ask in turn for what information or objects you wish to pass to the ChaseSomething<br />
method.<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\06\method-parameters.html<br />
31/03/2008
Chapter 6: Method Parameters<br />
The final 'generic' method<br />
It is also possible to use the method we have just created as an event method:<br />
The ChaseSomething method used in an event<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\06\method-parameters.html<br />
Page 5 of 5<br />
Prev | Up | Next<br />
31/03/2008
Chapter 6: Modeling<br />
Introduction to Programming<br />
Chapter 6: Method Parameters and Model l ing<br />
Modelling<br />
Modelling | Up<br />
Prev | 1 2 p | Next<br />
We have seen earlier that objects have properties. For example, our poor Cow has many<br />
properties including its shape, size and colour. The Cow also has parameters for its position,<br />
the direction it is facing and whether it is visible. To enable Alice to display a visual<br />
representation of a cow, all of the information that is required to model a cow is stored. Alice<br />
makes some of this information available to us in the properties tab. In this tab, we have<br />
methods that allow us to change the colour of an object, or an objects viability. Alice uses this<br />
information to model a world and the objects in it (for example, the position and colour of an<br />
object). In Alice, this model is presented to us visually.<br />
Part of the skill of programming is to use your imagination to see how a model can be built<br />
from stored information. When we are given a scenario, we can extract from it the objects we<br />
require. Then extract the storyboard and the sequence of events necessary to play the<br />
scenario out.<br />
Looking Back<br />
Think carefully about this: everything in the Alice world is<br />
simulated/modeled from stored information. All Alice really 'sees' about the<br />
modeled world is the stored information (and the code telling it how to use<br />
that information to, for example, display an object, and so on.)<br />
Take, for instance, the Robot-Alien scenario from week 1. We found that the objects in this<br />
scenario were the Robot-manned craft, a Robot, Rocks, an Alien and the Moon Landscape. We<br />
then wrote the storyboard for this scenario:<br />
Alien peeks out from behind rock<br />
The Robot is surprised<br />
Robot looks around<br />
Robot sees the alien<br />
Robot moves towards Alien<br />
Alien is frightened and hides.<br />
Page 1 of 3<br />
We are presented here with a simple scenario and storyboard. If we use our imagination on<br />
this scenario, questions like, "How big is the alien?", "What colour are the rocks?", and "How<br />
does a robot move?", need to be answered and added to the stored information in the<br />
program. We need to think beyond the scenario, to gather information about the objects in<br />
the world. This will enable a detailed model of each object in the world, and for the world in<br />
general to be assembled.<br />
Once we have this model, we can then start to write code to manipulate it. For instance, in the<br />
previous scenario one of the lines from the storyboard is, "The robot is surprised". How does a<br />
robot act when they are surprised? Does their expression change? If so, we need to write code<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\06\modelling.html<br />
31/03/2008
Chapter 6: Modeling<br />
that will make the robot look surprised. In this line then, we need to 'model' a surprised robot.<br />
Up to now we have been using a visual tool to display and manipulate this stored information.<br />
Not all programs can (or should) be represented visually. As a consequence of this, you need<br />
to move away from the visual representations that Alice provides. It's necessary to start<br />
thinking of what's required to model a scenario, at a more abstract level.<br />
For instance, what objects (and properties of each) are required to model the following<br />
scenarios:<br />
A bank account?<br />
A theatre booking office?<br />
A student enrollment program?<br />
An air traffic control system?<br />
Modelling<br />
Let's consider a (simple!) Air Traffic Control system; what objects are required?<br />
Aircraft<br />
Runways<br />
Flight Paths<br />
What properties do these objects have?<br />
Aircraft<br />
Runway<br />
Registration number<br />
Flight coordinates<br />
Scheduled arrival time<br />
Number<br />
Length<br />
Flight Path<br />
Height<br />
And for the Student Enrolment program, what objects are required?<br />
Students<br />
Subjects<br />
Courses<br />
What properties do these objects have?<br />
Student<br />
Subject<br />
Student number<br />
Name<br />
Address<br />
Enrolled course list<br />
Name<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\06\modelling.html<br />
Page 2 of 3<br />
31/03/2008
Chapter 6: Modeling<br />
Course<br />
Number<br />
Lecturer<br />
Room<br />
Name<br />
Number<br />
Subjects<br />
Course Leader<br />
The next stage in modeling a problem is to determine what methods we need to manipulate<br />
the objects and object parameters. For instance, with our student enrolment system, we most<br />
likely need methods to generate a unique student number, input the student name and<br />
address, input the course the student is enrolled in (among many others).<br />
How Does Modelling Tie In With Programming?<br />
Programming involves:<br />
1. Determining which aspects of the task we need to model.<br />
In the previous two scenarios we first looked at, what items were required to model the<br />
task? In the Air traffic control system the items may include the aircraft, runways and<br />
the planes coordinates<br />
2. Determining what information we require to build the model.<br />
For each item that forms part of our model we now need to model the required qualities<br />
of that part.<br />
3. Determining what code we need to manipulate the information and implement<br />
our model.<br />
In the Air traffic control scenario, there may be a requirement to continually update the<br />
coordinates of each aircraft in the current air space. As a programmer, we must be able<br />
to design and write code to implement each task in the program.<br />
4. Implementing and testing the model.<br />
It is important that at each stage in the program's implementation, that the code be<br />
tested to make sure there are no bugs, or errors that would cause a problem.<br />
(Especially with the air traffic control scenario!)<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\06\modelling.html<br />
Page 3 of 3<br />
Prev | Up | Next<br />
31/03/2008
Practical 6<br />
Introduction to Programming<br />
C ha p ter 6: Method Parameters and Modelling<br />
Pr actical Exercises<br />
Practical Exercises | Up<br />
Prev | 1 2 p | Next<br />
You are encouraged to discuss these questions and share useful information you've found with<br />
others in the discussion forum.<br />
Q1. Write a method comboLock.comboturn that turns a combo lock's dial a number of positions<br />
specified by a parameter. A single position is 1/40 of a revolution.<br />
Q2. Write a method, leap, that makes a Kangaroo leap a specified height for a specified<br />
distance.<br />
Q3. Write a method, levitate, that allows Mana to practice her telekinetic power for levitating<br />
objects. The method should be called when an object is clicked on (using the event "when<br />
mouse is clicked on anything do levitate..."). When the method is called, Mana turns to face<br />
the object and levitates it five times the object's height. The object then falls back to the<br />
ground.<br />
Q4. Write a method, patternskate, that makes an ice-skater skate in a specified pattern<br />
(triangle, square, pentagon, etc.) The pattern is specified by the number of sides the pattern<br />
has. If less than three sides are specified, the method should only print out an error message.<br />
The method should also allow you to specify the length (in meters) of a pattern's side.<br />
Q5. Extend your method from the previous question, so that the ice-skater now does a series<br />
of complete spins while completing the pattern. For every meter she covers, she does a<br />
complete spin.<br />
Q6. You have been asked to write a program that will control the time tabling for your states<br />
capital city's train system. What information will you need to effectively model this program?<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\06\practical.html<br />
Page 1 of 1<br />
Prev | Up | Next<br />
31/03/2008
Chapter 7: Property and Method Variables<br />
Introduction to Programming<br />
Chapter 7: Property and M ethod Varia bles<br />
At the completion of this weeks study students should.<br />
Have an understanding of the use of Property variables in a program<br />
Have an understanding of the use of method variables in a program<br />
Co urse Materials<br />
Online Course Material<br />
Please select a subtopic to view its contents.<br />
Property Variables<br />
Method Variables<br />
Tutorial and Practical Exercises<br />
Practical Exercises<br />
Additional Materials<br />
Reading References<br />
Property and Method Variables | Up<br />
Prev | 1 2 p | Next<br />
Textbook: "Learning to Program with Alice", W. Dann et al., Pearson Prentice Hall<br />
Chapter 10, pp250-261<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\07\index.html<br />
Page 1 of 1<br />
Prev | Up | Next<br />
14/04/2008
Chapter 7: Property Variables<br />
Introduction to Programming<br />
Chapter 7: P roperty and Method Variab le s<br />
Pro perty or Obje ct Variables<br />
Property Variables | Up<br />
Prev | 1 2 p | Next<br />
In last weeks <strong>material</strong>, we saw that Alice uses stored information to model a world and the objects within; for example,<br />
to display an object at a certain position, or to define the colour of an object. We saw that Alice uses this stored<br />
information to model an object and display it in a visual environment. Alice allows us to add further information to<br />
objects, in the form of additional properties. After adding an additional property to an object, the programmer is also<br />
required to add code to specify how the extra property is used.<br />
Scenario: Mana has just discovered that she has an identical twin sister Hana. But they need to have a way for each<br />
sister to remember their own name when they introduce themselves to other people.<br />
Mana and her twin Hana, but which is which?<br />
One way we can solve this problem is to define a new property variable for each of the sisters. A property variable<br />
allows an object to store unique information about itself. For this property variable, we need to store the sisters name<br />
as a string. To create a property variable, click on the object in the object window, then the properties tab in the object<br />
details window. Click on the button at the top of this window labeled create new variable.<br />
Create a new property for this object.<br />
The program can now access each sisters name, as shown below.<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\07\property-variables.html<br />
Page 1 of 6<br />
14/04/2008
Chapter 7: Property Variables<br />
Let's have a look at property variables in another scenario.<br />
A program to access the property variables.<br />
Page 2 of 6<br />
Scenario: In a fairground is a carousel that is operated by pulling a lever forward. This is to be done in the program by<br />
clicking on it with the mouse.<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\07\property-variables.html<br />
14/04/2008
Chapter 7: Property Variables<br />
The carousel operated by a lever.<br />
If you wish to follow this scenario on your computer, please download this <strong>file</strong>: carousel.a2w (right click and use save<br />
as)<br />
Note: do not use the carousel from alice in this scenario, as the carousel object in this <strong>file</strong> has been modified.<br />
In this scenario, we need to be able to move the lever forward to be able to start the carousel. We can do this by<br />
creating a method called MoveLever. Then this method can be used in a 'when the mouse is clicked on an object' event<br />
to start the carousel when the lever is moved forward.<br />
The method called MoveLever and the moveLever event.<br />
Page 3 of 6<br />
The MoveLever method, as we have it, now has a problem: the first time we click on the level, the handle turns<br />
forward. The next time we click on the lever, the handle moves forward again till finally the lever has turned enough to<br />
be under the ground. Obviously, we only want the lever to turn forward on the first click, then back to its original<br />
position on the next click. To do this, we need to know which direction to move the lever; this depends on its current<br />
position. If the lever is in the forward position, we need to move it backwards; and it should move forwards if in the<br />
backwards position.<br />
We learnt last week that objects can store information about themselves; for example their colour, size and visibility.<br />
This stored information about an object can be changed, for instance the colour of an object can be changed, or the<br />
visibility property of an object can be changed from true to false. We call these properties variables. We can change or<br />
vary the value of a variable. In the previous example, we created a myName property of type string for the sisters'<br />
names. This time, we need a property that will tell us if leverForward is true or false. To store true/false, the variable<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\07\property-variables.html<br />
14/04/2008
Chapter 7: Property Variables<br />
must be of type boolean.<br />
Create a property variable of type Boolean<br />
We now have a variable that can remember if the position of the lever is forward (leverForward = true) or backward<br />
(leverForward = false).<br />
The variable to remember the position of the lever<br />
We can now use this property variable to test if the lever is in the forward or backward position. By placing the variable<br />
in the test of an if statement (remember: the if test returns a true/false result). The test in our if statement is for 'if<br />
lever.leverForward' will give us a true or false value. If the if test returns false (meaning the lever is in the backward<br />
position), the lever is then turned forward, the value of leverForward is changed to true and the carousel animation is<br />
started. Once the animation has finished we can click on the lever a second time. This time, as levelForward is set to<br />
true, the if test returns true the lever is then moved backwards and the value of leverForward is reset to false.<br />
The leverForward variable used in an if statement<br />
Page 4 of 6<br />
It may be helpful to think of variables as "boxes" that can hold values of a particular type. In the first example, we<br />
created a box of type string that could hold the sisters name. In the second example, we had a box of type boolean that<br />
held a true/false value as to whether the lever was in the forward or backward position.<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\07\property-variables.html<br />
14/04/2008
Chapter 7: Property Variables<br />
It may be helpful to think of a variable as a box<br />
There are times where we need to count how many times a certain action has occurred. To do this, we can use a<br />
property variable of type number. This can be set to a starting value, and incremented each time a certain action or<br />
event has occurred, as we will see in the following example.<br />
Scenario: In a fairground is an old carousel that is operated by pulling a lever forward. The carousel is so old it needs to<br />
be given a 10 minute (10 second) rest after every 5 uses.<br />
For this scenario, we need to be able to count the number of times the carousel has been used. To do this, we need to<br />
add a numeric property variable to the lever object. We can then increment this newly created carouselRun variable<br />
each time the lever is moved to the forward position. This variable will store the number of times the carousel has been<br />
used.<br />
Adding a property variable to act as a counter<br />
Page 5 of 6<br />
Once the value in the carouselRun variable is greater than 5, the program pauses for the required time and the lever<br />
cannot be operated till after a delay. Note: I have also included a number of print statements to display the value of the<br />
carousel counter.<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\07\property-variables.html<br />
14/04/2008
Chapter 7: Property Variables<br />
The carouselRun counter used to count the number of times the lever is moved forward<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\07\property-variables.html<br />
Page 6 of 6<br />
Prev | Up | Next<br />
14/04/2008
Chapter 7: Method Variables<br />
Introduction to Programming<br />
Chapter 7: Property and Method V a r iable s<br />
M ethod V a riables<br />
Method Variables | Up<br />
Prev | 1 2 p | Next<br />
There may be times when we need to remember some information while code is running within a method. For<br />
example; the results of a calculation, or intermediate calculations that can be combined to form the final result.<br />
Sometimes we may need to use the result of a calculation a number of times in the same method. In each of<br />
these situations, we can use a method variable to store the result and reuse it at a later point in the program. We<br />
can also access the same method variable many times within a method, this will avoid having to calculate the<br />
same result each time we require the result of the same calculation.<br />
A method variable only exists while the code is running within the method in which it has<br />
been defined. Once the code has finished in a method, all values stored within a method<br />
variable are lost.<br />
Think of method variables as "throw away" variables.<br />
Scenario: Clara the jumping cow is learning the high jump for the Cow Olympics. But she needs someone to<br />
estimate the height before she will attempt the jump.<br />
The initial set up for the cow highjump<br />
Page 1 of 5<br />
In this scenario we need to get the user's input for the estimated height. We need a method variable to store this<br />
value, prior to using it in the program.<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\07\method-variables.html<br />
14/04/2008
Chapter 7: Method Variables<br />
Creating a number method variable to store the estimated height<br />
Because we have stored the user input for estimated height in a method variable, we are now able to access this<br />
value multiple times within the method. Remember though, once the program has finished, the method variable<br />
ceases to exist, its stored value is lost, and the data must be reinput the next time this method is called. Below is<br />
the final cowJump method:<br />
The cowJump method<br />
We can also use a method variable to store a random number. Then we are able to use this stored value<br />
anywhere in in the current method that a numeric variable can legally be used.<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\07\method-variables.html<br />
Page 2 of 5<br />
14/04/2008
Chapter 7: Method Variables<br />
Note: in the above example, we have had to use multiple nested if statements to test each possibility of the<br />
random number. Then once the program has found a test that evaluates true, the commands for that particular if<br />
statement are executed. All other commands are skipped over.<br />
Tips and Tricks<br />
Creating and using a method variable to store a random number<br />
There may be times in a program that you need to swap two variables. A method variable can be used to provide<br />
temporary storage in this situation. Let's see how this works in a short program.<br />
Swapping two numbers (frame every 5 seconds)<br />
In the above animation the variables num1 and num2 are first set to the values 10 and 20 respectively. The next<br />
step is to copy the value from num1 into the temp variable. Having done this, we can now overwrite the value in<br />
num1 with the value in num2 (we have the value that is in num1 stored in the temp variable so it won't be lost).<br />
The last step is to copy the value from the temp variable into the num2 variable.<br />
Method Variables and Property Variables: An Important Difference<br />
Page 3 of 5<br />
In the following example we have created a method called myTest. In this method we have created a method<br />
variable called testV which is initialized to the value 1. We then change the value in this variable to 2.<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\07\method-variables.html<br />
14/04/2008
Chapter 7: Method Variables<br />
If we print out the value in the method variable, the value of 2 is printed. Once we have finished the code in<br />
myTest, the program returns to world.my first method. If we then print out the value in testV the result is 1.<br />
Although method myTest changed the value in testV from 1 to 2, all changes to testV vanished after the method<br />
myTest has finished running. This differs from object property variables in that the value in a object property<br />
variable exists for as long as the object exists.<br />
Passing Method Variables as Parameters<br />
Method myTest including a method variable<br />
The code in method world.my first method<br />
The code in method world.my first method<br />
We have seen earlier that we can pass information into methods as input parameters.<br />
Creating a new parameter<br />
Page 4 of 5<br />
These parameters can be objects, or some other simple information (such as numbers or strings). In the following<br />
example, we have created a variable in world.my first method called num and initialized it to the value of 10. We<br />
have also created a method called testMethod1 that has a numeric input parameter. In this example we have<br />
used the method variable num as the input parameter to world.testMethod1. note again the values in the<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\07\method-variables.html<br />
14/04/2008
Chapter 7: Method Variables<br />
printout, the value of data that gets set to 20 is lost once testMethod1 has ended.<br />
The two methods and the print out from the previous example<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\07\method-variables.html<br />
Page 5 of 5<br />
Prev | Up | Next<br />
14/04/2008
Practical 7<br />
Introduction to Programming<br />
Chapter 7: Property and M ethod Varia bles<br />
Practical Exercises<br />
Practical Exercises | Up<br />
Prev | 1 2 p | Next<br />
Q1. A horse is in a field containing a crate and a fence. Write two methods jump and runat.<br />
Method jump takes a number parameter, the height to jump. The jump occurs over 2 meters.<br />
Method runat makes the horse run at an object (given as a parameter) - the horse runs in<br />
steps of 1 meter until it is 1.5 meters from the object - then it will jump the object.<br />
Q2. You've seen in the notes how world method ask user for a number can be used to obtain<br />
a number from the user, and store it in a variable. Design a method that will get a valid PIN<br />
number from the user. Valid PIN numbers are numbers in the range 1111 to 9999 inclusive.<br />
You can assume the user will enter an integer. If the user enters an invalid PIN (e.g. 98), they<br />
should receive an error message and be told to enter another number. This should be<br />
repeated until the user enters a valid number.<br />
Q3. Design a program that will randomly generate a number between 1 and 9 inclusive. The<br />
program will then play a guessing game with the user until they guess the number. The user<br />
is asked to enter a number from 1..9. You can assume the user will enter an integer. The<br />
program should ensure the user number is between 1 and 9 inclusive, giving the user an error<br />
message until they get it right. The program then tells the user if the guess was too high or<br />
too low. If the guess was high or low, the user is asked to guess again. The game ends when<br />
the user guesses the number.<br />
Q4. Using the <strong>file</strong> Kangaroo Jump construct a program to instruct the kangaroo to jump from<br />
the ground to the first crate then onto the second crate. Each jump will require user input for<br />
height and length of the jump. Your solution must use method parameters and variables. This<br />
avi movie shows the program running. KangaJump<br />
Q5. Modify the program in question 4 so that when the kangaroo jumps off the second crate<br />
after a delay of 5 seconds after landing on it he returns to the original position (the invisible<br />
cone might be of use in this.)<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\07\practical.html<br />
Page 1 of 1<br />
Prev | Up | Next<br />
14/04/2008
Chapter 8: Functions - Returning a Value<br />
Introduction to Programming<br />
Chapter 8: Functions - Returning a Value<br />
At the completion of this weeks study students should.<br />
Functions - Returning a Value | Up<br />
Prev | 1 p | Next<br />
Understand that a function may be used to information about an object or the result of a<br />
calculation<br />
Be aware that functions may also have input parameters<br />
Know how to create and use a function in a program<br />
Be aware that functions must return information<br />
Co urse Materials<br />
Online Course Material<br />
Please select a subtopic to view its contents.<br />
Writing and Using Functions<br />
Tutorial and Practical Exercises<br />
Practical Exercises<br />
Additional Materials<br />
Reading References<br />
Textbook: "Learning to Program with Alice", W. Dann et al., Pearson Prentice Hall<br />
Chapter 6, pp147-159<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\08\index.html<br />
Page 1 of 1<br />
Prev | Up | Next<br />
21/04/2008
Chapter 8: Writing and using Functions<br />
Introduction to Programming<br />
Chapter 8: F unctions - Re t ur ni n g a Value<br />
W rit ing and U sing Functions<br />
Writing and Using Functions | Up<br />
Prev | 1 p | Next<br />
Functions allow us to obtain information about an object, or the world an object is in. This may perform<br />
simple functions, such as to return information about the properties of an object. We can also use a function<br />
to obtain the result of a calculation or to provide us with a true/false choice. We have used functions many<br />
times in the past weeks, When asking the user for a number, we use the 'ask user for a number' function to<br />
return a value. We have used 'distance in front of' to obtain a numeric value of the distance between two<br />
objects. We have also used the math functions from 'world' to test if two values are equal or if one value is<br />
greater than another.<br />
Creating New Functions<br />
Examples of functions with an object and 'world.math' functions<br />
Alice allows us to create new functions both in an objects function area, and in the worlds function area. In<br />
an object's details window, within the function tab there is a button labeled 'create new function'. Clicking on<br />
this button will open a window that allows the details of the new function to be entered. Let's have a look at<br />
this in practice.<br />
The create new function button<br />
Page 1 of 4<br />
Scenario. A mad scientist is being chased by a zombie; if the zombie gets to within 1 meter of the scientist,<br />
the scientist will be caught. We need to know if the scientist is in danger of being caught (if the zombie is<br />
within 3 meters).<br />
We can translate this problem into a function that will give us a true/false indication of whether the scientist<br />
is in danger. As we have seen earlier, click on the 'create new function' button and enter the name for the<br />
new function and the return type. In this case select boolean (as we require a true/false result) and we'll call<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\08\writing-functions.html<br />
21/04/2008
Chapter 8: Writing and using Functions<br />
this function 'is in danger'.<br />
The create new function dialogue box<br />
In previous weeks we have used the 'distance to' method to find out how far one object is from another. In<br />
this instance we need to compare this value with the value inside which the scientist IS in danger. This will<br />
give us a true/false resul, based on the distance between the scientist and the zombie.<br />
A function MUST return a value. This can be a number, a boolean (true/false) value, an<br />
object or other miscellaneous type (including string)<br />
In the above example we are only able to discover if the scientist is in danger from the zombie. What if<br />
multiple monsters were chasing the scientist? Fortunately, functions allow us to pass parameters to them. In<br />
this case we could add a parameter (for a monster) that we can use to check with.<br />
The monster who is chasing the scientist passed to the function as a parameter<br />
Page 2 of 4<br />
Within the function, we can use most control structures (including loops and if statements) that are available<br />
to us in other areas of code. We are also able to include variables within functions. The following function<br />
uses a control structure (a loop) and a variable to obtain a valid number in the range 1 to 10. We can see<br />
the loop test will result in true (continuing the loop) if the number is less than 0, or the number is greater<br />
than 10. This means that the function will not finish until a number within the proper range is entered.<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\08\writing-functions.html<br />
21/04/2008
Chapter 8: Writing and using Functions<br />
Functions can contain variables, loops etc.<br />
Functions can also contain more than one return statement. The following example converts between a<br />
numeric value and its string equivalent for numbers between 1 and 5. Once the test in any of the if<br />
statements returns true, the function will immediately return the corresponding text value. No lines of code<br />
will be executed beyond that point - a function cannot return more than one value.<br />
We can also use multiple return statements in a function.<br />
Page 3 of 4<br />
We have used functions in earlier exercises to return a value. Functions that you create are used in the same<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\08\writing-functions.html<br />
21/04/2008
Chapter 8: Writing and using Functions<br />
manner. We are able to use these functions anywhere that a value is required. In this example, we use the<br />
'numToString' function to provide a countdown prior to the helicopter taking off. The full program is in<br />
copterTakeOff.a2w (right click and select 'save as')<br />
In this example, we have a new function that calculates the length of the hypotenuse (diagonal) of a rightangled<br />
triangle from the two sides passed in as parameters. The return value from this function is then<br />
displayed within the main program. The full program is contained in Hypotenuse.a2w (right click and select<br />
'save as')<br />
Important Things to Remember<br />
Using the numToString function in a program<br />
The function to calculate the length of the hypotenuse<br />
The return statement in a function can only return one piece of information.<br />
If you require to return more than one piece of information from a function, this cannot be done using return<br />
values. Use a method with an object type as its parameter, then change the objects property variables<br />
within the method before returning it.<br />
Generally, it is considered poor programming for a function to alter any object's property. The only effect a<br />
function should have on the world around it is to return a value. This value can be numeric, boolean<br />
(true/false) or any number of other types of information.<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\08\writing-functions.html<br />
Page 4 of 4<br />
Prev | Up | Next<br />
21/04/2008
Practical 8<br />
Introduction to Programming<br />
C ha p ter 8: Functi ons - Returning a Val ue<br />
Pr actical Exercises<br />
Aim: To investigate functions.<br />
Practical Exercises | Up<br />
Prev | 1 p | Next<br />
Q1. A Kangaroo needs to know how high to jump, in order to clear various objects. When<br />
presented with an object, the Kangaroo wishes to jump 1.5 times the height of the object.<br />
Design a function with an object parameter (called item). The function will determine how high<br />
the Kangaroo must jump in order to clear the item.<br />
Q2. In question 2 of last weeks Practical you were asked to "design a method that will get a<br />
valid PIN number from the user. Valid PIN numbers are numbers in the range 1111 to 9999<br />
inclusive. You can assume the user will enter an integer. If the user enters an invalid PIN (e.g.<br />
98), they should receive an error message and be told to enter another number. This should be<br />
repeated until the user enters a valid number." Alter your solution so it is now implemented by<br />
a function. The function returns the valid PIN number to World.myfirstmethod, where it is then<br />
printed.<br />
Q3. A hungry rabbit is asking for the user's help in selecting objects to eat. The user nominates<br />
an item for the rabbit to eat by clicking on the item. Design a function that will return whether<br />
the rabbit should eat the item or not (the item is passed to the function - you only need to<br />
design the function, not the entire program). Edible objects are daisy, purpleFlower, redFlower,<br />
and flower.<br />
Q4. A magic square is a n *n sized grid of integers, where each row, column and the two<br />
diagonals all add up to the same number. For example, the following is a magic square:<br />
2 7 6<br />
9 5 1<br />
4 3 8<br />
Write a Boolean (i.e. one that returns true or false) function to determine if a 3 * 3 grid is a<br />
magic square. The grid is made of number variables (numpos0, numpos1..numpos8) - you can<br />
assume these variables are World properties.<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\08\practical.html<br />
Page 1 of 1<br />
Prev | Up | Next<br />
21/04/2008
Chapter 9: Comparing Alice to Java<br />
Introduction to Programming<br />
Chapter 9: Comparing Alic e to Java<br />
At the completion of this weeks study students should.<br />
Be aware of many programming languages<br />
Understand the differences between Alice and Java environments<br />
Be able to get input from the user using Java<br />
Be able to use if statements within a java program<br />
Co urse Materials<br />
Online Course Material<br />
Please select a subtopic to view its contents.<br />
Other Programming Languages<br />
Alice and Java<br />
Reading Input<br />
Tutorial and Practical Exercises<br />
Tutorial Exercises<br />
Practical Exercises<br />
Additional Materials<br />
There are no additional <strong>material</strong>s available at this time.<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\09\index.html<br />
Page 1 of 1<br />
Comparing Alice to Java | Up<br />
Prev | 1 2 3 t p | Next<br />
Prev | Up | Next<br />
28/04/2008
Chapter 9: Alice and Java<br />
Introduction to Programming<br />
Chapter 9: Comp a ring Alice to Java<br />
Alice and Java<br />
Alice and Java | Up<br />
Prev | 1 2 3 t p | Next<br />
Up to now you have been using Alice to learn the underlying concepts of computer programming. These<br />
fundamental programming building blocks (variables, if statements and loops) can be applied to almost any<br />
other programming language. In the next few weeks we will apply these concepts to a commercial<br />
programming language known as Java. With Alice, you have been able to see the visual result of your code;<br />
for instance, an object moving, or the visibility of an object changing. When you are programming Java this<br />
is not the case; you will have to use your imagination to see how variables and code produce the final<br />
program.<br />
With Alice you have been using 'drag and drop' statements to build a program with very little chance of<br />
getting syntax errors. This is not the case with Java, as the program code is written in an editor. As a result<br />
it is very easy to create illegal statements (syntax error).<br />
Objects in Alice and Java<br />
Both Alice and Java are object oriented languages. In Java there are the familiar concepts you have seen in<br />
Alice; methods, parameters, variables, and so on. In Alice we saw that all information regarding an object is<br />
stored in that particular object. We can think of this as a blueprint or plan of that object.<br />
The builder of a house works from a blueprint<br />
Page 1 of 6<br />
A builder of a house works from a blueprint that provides information about exactly how it will look. The<br />
blueprint gives details of sizes, <strong>material</strong>s, colours and other 'parameters' that go together to form the final<br />
'object' (the house). In Alice and Java this 'blueprint' is called a class.<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\09\alice-and-java.html<br />
28/04/2008
Chapter 9: Alice and Java<br />
All the programs you have written in Alice have had at least one object; the world object. This is the same<br />
with Java programs, they must also have a starting object (called a class). Within the class, the program<br />
enables us to develop the blueprint for that class by defining object properties and methods to manipulate<br />
them. We can name this starting object anything we want (not just world as it is in Alice).<br />
Let's take the example of the standard "Hello World" program. We first need a class, which we could call<br />
HelloWriter.<br />
The first line allows the program to use the java methods it requires. In this case we are only printing to the<br />
screen, so the only java methods we require are the input/output methods. When saving this <strong>file</strong> it must be<br />
given the same name as the class - HelloWriter.java.<br />
MyFirstMethod Equivalent<br />
An object's blueprint in Alice and Java is called a class<br />
import java.io.*;<br />
// Tells Java where to find details about how to print to the screen<br />
public class HelloWriter<br />
{<br />
// Methods for HelloWriter are described here<br />
}<br />
The // at the start of a line tells Java that it is a comment, and should be ignored by<br />
the computer.<br />
In previous weeks when you have run programs written in Alice they have usually started running at<br />
world.myFirstMethod. As with Alice, Java programs must have a starting point. In Java, this is called main().<br />
import java.io.*;<br />
public class HelloWriter<br />
{<br />
public static void main(String[] args)<br />
{<br />
System.out.println("Hello World");<br />
}<br />
}<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\09\alice-and-java.html<br />
Page 2 of 6<br />
28/04/2008
Chapter 9: Alice and Java<br />
Object Property Variables<br />
In Alice we have added property variables to objects to enable us to store additional information about an<br />
object. Java allows us to create property variables within a class. As with Alice, these property variables can<br />
be of any variable type that is available to us, for example string or integer.<br />
In the previous example, a class called NumberWriter has been defined which includes a property variable<br />
called age.<br />
In the above program the line static int age requests a variable of type integer called age. The line<br />
System.out.print() prints the required text to the screen. Note: the two uses of System.out.print()<br />
(prints without the new line character at the end of the line), and System.out.println() (includes a new<br />
line at the end of the line).<br />
Method Variables<br />
The equivalent program in Alice<br />
Alice Java<br />
Class name world HelloWriter<br />
Starting point myFirstMethod main()<br />
import java.io.*;<br />
public class NumberWriter<br />
{<br />
//property variables go here<br />
static int age;<br />
public static void main(String[] args)<br />
{<br />
age = 21;<br />
System.out.print("Property variable age is ");<br />
System.out.println(age);<br />
}<br />
}<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\09\alice-and-java.html<br />
Page 3 of 6<br />
28/04/2008
Chapter 9: Alice and Java<br />
import java.io.*;<br />
public class VarDemo<br />
}<br />
public static void main(String[] args)<br />
{<br />
// a method variable inside the main method<br />
int num;<br />
num = 2;<br />
System.out.println(num);<br />
}<br />
}<br />
In week 7 we saw that method variables can be used in methods as a temporary storage (remember: their<br />
value is lost once the method has finished running). In the above programs a method variable called num has<br />
been defiined and set to 2; the variable is then printed to the screen.<br />
IF statements in Alice and Java<br />
Instruction in Alice instruction in java Meaning<br />
if(num > 1) if the value in variable num is greater than 1<br />
if(num >= 1) if the value in variable num is greater than or equal to 1<br />
if(num < 1) if the value in variable num is less than 1<br />
if(num
Chapter 9: Alice and Java<br />
When the program requires an if..else statement, two sets of braces must be used, one around each block of<br />
code.<br />
Alice and Java AND test<br />
Both AND tests and OR tests are slightly different in Alice and in Java, as the following two examples<br />
demonstrate.<br />
AND<br />
if (numA > numB)<br />
{<br />
System.out.println("In this method");<br />
System.out.println("numA is greater than numB");<br />
}<br />
An if..else statement in Alice<br />
if(numA > numB)<br />
{<br />
System.out.println("In this method");<br />
System.out.println("numA is greater than numB");<br />
}<br />
else<br />
{<br />
System.out.println("In this method");<br />
System.out.println("numA is less than or equal to numB");<br />
}<br />
By placing a block of code inside braces, we are telling Java that a particular 'block' of<br />
code belongs to either the true or false part of the if statement.<br />
if(numA >= 1 && numA
Chapter 9: Alice and Java<br />
Note the two ampersands (&&): this is the code for AND in Java<br />
OR<br />
{<br />
}<br />
System.out.println("in this method");<br />
System.out.println("the value of numA is between 1 and 10");<br />
An OR test in Alice<br />
if(numA < 1 || numA > 10 )<br />
{<br />
System.out.println("In this method");<br />
System.out.println("The value of numA is NOT between 1 and 10");<br />
}<br />
In Java, the code for OR is '||' (two pipe characters; shift-backslash on most keyboards)<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\09\alice-and-java.html<br />
Page 6 of 6<br />
Prev | Up | Next<br />
28/04/2008
Chapter 9: Reading Input<br />
Introduction to Programming<br />
Chapter 9: Compari ng Alice t o J ava<br />
Readin g in p ut<br />
Reading Input | Up<br />
Prev | 1 2 3 t p | Next<br />
In this <strong>subject</strong> you are not expected to write methods to get input from the user. A <strong>file</strong> called<br />
ConsoleReader.java has been provided for that purpose. Download the <strong>file</strong> here ConsoleReader.java<br />
(Right click and save as) keep this <strong>file</strong> in a safe place, you will use it in many of the java programs.<br />
Console reader contains 2 methods, readLine() which reads a line of text and the method we will be<br />
using readInt() which reads an integer (a number) from the keyboard. If you need to get user input<br />
within a program you will need to place ConsoleReader.java in the same directory as your java program<br />
<strong>file</strong>. You will also need to have created a ConsoleReader object in your program to handle input from<br />
the keyboard. (more on that later)<br />
In week 7 we had an example of "Clara the jumping cow" where the user was asked for the height of<br />
the bar. let's have a look at that again but this time we'll just print the value the user has input.<br />
ConsoleReader console = new ConsoleReader();<br />
Here we are asking for a ConsoleReader object which is contained in the ConsoleReader.java <strong>file</strong>. Once<br />
we have created the ConsoleReader object we are then able to use the methods within the object. This<br />
is very similar to Alice, in that we first had to place an object in the world before we were able to use<br />
the methods contained in that object.<br />
console.readInt()<br />
Reading user input in Alice<br />
import java.io.*;<br />
public class GetHeight<br />
{<br />
public static void main (String[] args)<br />
{<br />
int height;<br />
ConsoleReader console = new ConsoleReader();<br />
System.out.print("How high is the bar? : ");<br />
height = console.readInt();<br />
System.out.println("The value you entered was " + height);<br />
}<br />
}<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\09\reading-input.html<br />
Page 1 of 2<br />
28/04/2008
Chapter 9: Reading Input<br />
Here we are using a method contained in the ConsoleReader object. readInt(), reads an number from<br />
the user and in this case stores it in variable height.<br />
You will need to include ConsoleReader.java in the same directory as your Java<br />
program, in order for this to work correctly.<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\09\reading-input.html<br />
Page 2 of 2<br />
Prev | Up | Next<br />
28/04/2008
Tutorial 9<br />
Introduction to Programming<br />
Chapte r 9: Com p aring Alice to Java<br />
Tutorial Exercises<br />
Installing Eclipse and the Java Runtime Environment (JRE)<br />
Downloading and installing the Java Runtime Environment<br />
Tutorial Exercises | Up<br />
Prev | 1 2 3 t p | Next<br />
The following instructions are for Windows. For any other operating system please consult the system manual<br />
for directions of how to install software.<br />
For the rest of the course we will be also writing programs in Java. For this you will need to download the Java<br />
runtime environment. This is available from the sun download page at<br />
http://www.java.com/en/download/manual.jsp and click on the appropriate version for your operating<br />
system.<br />
Click on the appropriate JRE for your operating system<br />
Page 1 of 5<br />
A box will ask you if you want to run or save the <strong>file</strong>. Select save. Another box will popup and ask you where<br />
to save the <strong>file</strong>. Select a location where you will be able to find the <strong>file</strong> later and click on OK.<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\09\tutorial.html<br />
28/04/2008
Tutorial 9<br />
Find the <strong>file</strong> you have previously downloaded, double click on it and follow the installation instructions.<br />
Downloading and installing Eclipse<br />
Click on save<br />
Once you have downloaded and installed the JRE you can download and install Eclipse. This is available for<br />
download from http://www.eclipse.org/downloads/, click on the appropriate version for your operating<br />
system. Remember to select 'Eclipse IDE for Java Developers'.<br />
The Eclipse download page<br />
Page 2 of 5<br />
A page will open asking you where you want to download eclipse from (usually the selected site is the closest<br />
to your location) click on the selected download location.<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\09\tutorial.html<br />
28/04/2008
Tutorial 9<br />
A box will then popup and ask you if you want to run or save the <strong>file</strong>. Select Save. Another box will popup and<br />
ask you where to save the <strong>file</strong>. Select a location where you will be able to find the <strong>file</strong> later and click on OK.<br />
For students using any other operating system than Windows, please refer to the system manuals for how to<br />
install software.<br />
Extracting the Eclipse Archive<br />
Select the location to download from<br />
Click on save<br />
Page 3 of 5<br />
The copy of Eclipse that you have downloaded comes as a zip <strong>file</strong>. Students that are using windows XP or later<br />
have a zip extraction program as part of Windows, and the following procedure should be close to what you<br />
will need to follow. For students that do not have a zip extractor built in to Windows either download<br />
FreeByteZip (right click and select save) or go to their download page at http://www.freebyte.com/fbzip/.<br />
Start FBZip by double clicking on the <strong>file</strong>. You will be asked to 'Choose one of the following actions' select -<br />
Open an existing archive.<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\09\tutorial.html<br />
28/04/2008
Tutorial 9<br />
Find the copy of eclipse you have previously downloaded, click on it and select open.<br />
Click on the extract icon.<br />
Select open an existing archive<br />
Find the copy of Eclipse, select it and click on open<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\09\tutorial.html<br />
Page 4 of 5<br />
28/04/2008
Tutorial 9<br />
Click on the extract icon<br />
A popup will ask where you want the <strong>file</strong>s to be extracted to, select C drive and make sure that 'Extract all<br />
<strong>file</strong>s' and 'Use full path of <strong>file</strong>s' is selected. Click on ok to extract the <strong>file</strong>s from the Eclipse <strong>file</strong>.<br />
Extract Eclipse from the zip <strong>file</strong><br />
You will now need to create a shortcut to the program. Open my computer and locate the directory with the<br />
<strong>file</strong>s you have just extracted (if you have followed this setup they will be in C:\eclipse) double click on the<br />
Eclipse directory to open it. in this directory will be a <strong>file</strong> called eclipse.exe (This <strong>file</strong> will have a round purplish<br />
icon). Right click on the <strong>file</strong> and select 'create shortcut'. Click and drag the shortcut to the desktop.<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\09\tutorial.html<br />
Page 5 of 5<br />
Prev | Up | Next<br />
28/04/2008
Practical 9<br />
Introduction to Programming<br />
Cha pt er 9: Compa rin g Al ice to Java<br />
Pr ac ti ca l Ex er cises<br />
Starting Eclipse<br />
Practical Exercises | Up<br />
Prev | 1 2 3 t p | Next<br />
Double click on the Eclipse icon you previously created. The first screen you see will ask you to create or select a workspace. Click on OK. This will<br />
create a workspace in MyDocuments for your work.<br />
Create a workspace for your Java programs<br />
Once you have created your workspace the Eclipse IDE will startup and, if this is the first time you have used eclipse a welcome screen will be<br />
displayed.<br />
The Eclipse welcome screen<br />
If the welcome screen is displayed, click on the Workbench icon on the right of the screen.<br />
Page 1 of 7<br />
Once the workbench screen is displayed you will be presented with the default workbench (shown below). Before you can use this screen you will<br />
need to have created a new project.<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\09\practical.html<br />
28/04/2008
Practical 9<br />
Creating a New Project in Eclipse<br />
A project is an area where you can group programs together. For instance - All Java programs you write in this <strong>subject</strong> can be grouped under the<br />
same project. Firstly click on <strong>file</strong> on the menu bar at the top of the screen. select new and then select project.<br />
You will need to create a new Java project, this is under the Java tab.<br />
The default Workbench screen<br />
Select, <strong>file</strong> - new - project<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\09\practical.html<br />
Page 2 of 7<br />
28/04/2008
Practical 9<br />
Select Java project<br />
You will then be taken to the Java project wizard. For this <strong>subject</strong> you will only need to give the project a name (I suggest <strong>CPT120</strong>_exercises).<br />
Once you have done that click on the 'Finish' button.<br />
The Java project wizard<br />
Page 3 of 7<br />
Once you have created the new project it will be added to the 'Package explorer' window on the workbench. You will then be able to add new<br />
classes to the project.<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\09\practical.html<br />
28/04/2008
Practical 9<br />
Define a New Class and Add it to the Explorer Window<br />
The workbench with the new project added to the explorer window<br />
Creating a new class is similar to the task you have just done. For a new class once again click on <strong>file</strong> on the menu bar and select new. This time<br />
select class.<br />
Select, <strong>file</strong> - new - class<br />
Page 4 of 7<br />
Once you have selected new class you will be taken to the new class wizard. This wizard allows you to customize the new class to your<br />
requirements. For this <strong>subject</strong> we need to give the class a name (for your first Java program name the class hello) also select the main method<br />
stub. Once you have done this click on the finish button. (Ignore the warning about the default package)<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\09\practical.html<br />
28/04/2008
Practical 9<br />
Once you have completed this the workbench will look as below.<br />
Your first Java program "Hello World"<br />
The create new class Wizard<br />
the workbench set up with the new project and the new class<br />
In the previous section you created a new class called 'hello'. Go to the main method block and type in the line System.out.println("Hello<br />
World !!!") - for now do not put the ';' on the end of the line.<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\09\practical.html<br />
Page 5 of 7<br />
28/04/2008
Practical 9<br />
The "Hello World" program with errors<br />
Now click on the save icon or click on <strong>file</strong> - save, note that the syntax checker has highlighted the errors as shown below. You can see a<br />
description of the errors by placing the mouse over the error flag in the editor window<br />
An error in the program found by the syntax checker<br />
Page 6 of 7<br />
Now go to the line you previously entered and type the ';' on the end and save the <strong>file</strong> again. If no errors are reported we can then run the 'Hello<br />
class. Click on the icon with the white arrow on a green background. The output from the program will be displayed in the console area at the<br />
bottom of the screen.<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\09\practical.html<br />
28/04/2008
Practical 9<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\09\practical.html<br />
Page 7 of 7<br />
Prev | Up | Next<br />
28/04/2008
Chapter 10: Java Loops and Methods<br />
Introduction to Programming<br />
Chapter 10: Java Loops and Methods<br />
At the completion of this weeks study students should.<br />
Understand for and while loops in Java<br />
Understand the use of methods in Java<br />
Understand the use of method parameters in Java<br />
Understand the common mistakes that can occur in Java<br />
Co urse Materials<br />
Online Course Material<br />
Please select a subtopic to view its contents.<br />
Looping in Alice and Java<br />
Java Examples<br />
Practical Exercises<br />
Practical Exercises<br />
Additional Materials<br />
There are no additional <strong>material</strong>s available at this time.<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\10\index.html<br />
Page 1 of 1<br />
Up | Site Map<br />
Up | Site Map<br />
5/05/2008
Chapter 10: Java For Loops<br />
Introduction to Programming<br />
Chapter 10: Java Loops and Methods<br />
Looping in Alice and Java<br />
The For Loop<br />
Looping in Alice and Java | Up<br />
Prev | 1 2 p | Next<br />
In week 4 you were introduced to loops. We found if we needed to repeat a section of code a<br />
fixed number of times, we could use a for loop to accomplish this task. In Java, a for loop has<br />
the same sections as one in Alice. That is we have a initialisation section, the test section and<br />
the increment. In this example, the same code is displayed in both Alice and Java.<br />
The output from both of these programs is shown below, the full Java code can be downloaded<br />
here forLoop.Java (right click and save as)<br />
The While Loop<br />
A simple for loop in Alice<br />
int index;<br />
for(index = 0; index < 5; index = index + 1)<br />
{<br />
System.out.println("In the loop - The value of index is " + index);<br />
}<br />
The output of both of the above programs (shown in Alice)<br />
Page 1 of 6<br />
The syntax of while loops in Java is also very similar to those in Alice. The code below shows<br />
the same while loop implemented in the two languages. And like the previous example, the<br />
while loop in Java is configured with the same sections as in Alice.<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\10\for-loops.html<br />
5/05/2008
Chapter 10: Java For Loops<br />
The output from both of these programs is shown below (Alice output shown). The full Java<br />
program can be downloaded here WhileLoop.Java (right click and save as)<br />
Metho ds in Alice and Java<br />
A while loop in Alice<br />
numA = 0;<br />
while ( numA < 5 )<br />
{<br />
System.out.println("In the loop - The value of numA is " + numA);<br />
numA = numA + 1;<br />
}<br />
The output from the while loop example (Alice output shown)<br />
In the <strong>material</strong> for week 2, we looked at object methods. We used methods in Alice to<br />
manipulate the properties of an object. We say in Alice that methods may have input<br />
parameters. Let's first compare a method without parameters in both Alice and Java.<br />
A method without parameters in Alice<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\10\for-loops.html<br />
Page 2 of 6<br />
5/05/2008
Chapter 10: Java For Loops<br />
import Java.io.*;<br />
public class SayHi()<br />
{<br />
public static void sayHi()<br />
{<br />
/* \" prints the " character */<br />
System.out.println("In method sayHi - \"Hi\"");<br />
}<br />
}<br />
public static void main(String[] args)<br />
{<br />
sayHi();<br />
}<br />
In Java, a method is called in the same way as we would call a method in Alice. We can see in<br />
the Java main, the text sayHi() has been used to call the method called sayHi(). The code<br />
for this example can be downloaded here SayHi.Java (right click and save as)<br />
We can also write methods with input parameter(s) in the following example:<br />
SayHi_param.Java<br />
Page 3 of 6<br />
We pass into the method the number of times the loop is to run. Of note in this example is the<br />
placement of the increment line. In previous while loops, this line has been at the end of the<br />
loop. In this example the increment is at the start; this means that in the last iteration of the<br />
loop, the value of count will be incremented to equal numTimes.<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\10\for-loops.html<br />
5/05/2008
Chapter 10: Java For Loops<br />
An Alice method with an input parameter<br />
public static void printHello(int(numTimes)<br />
{<br />
int count;<br />
}<br />
count == 0;<br />
while ( count < numTimes )<br />
{<br />
count = count + 1;<br />
if( count == numTimes )<br />
{<br />
System.out.println("The while loop has finished");<br />
}<br />
else<br />
{<br />
System.out.println("In method printHello - \"Hello\" " + count);<br />
}<br />
}<br />
Notice in the above Java example, the brackets around the while loop this<br />
means, "do all this within these brackets." Notice also the indentation of<br />
the brackets and code, this makes the code much easier to read and allows<br />
us to know exactly which statements belong to each part of the loop or if<br />
statement.<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\10\for-loops.html<br />
Page 4 of 6<br />
5/05/2008
Chapter 10: Java For Loops<br />
The output of this method is shown below, from Alice. The full Java code for this method is<br />
downloadable here SayHi_Param.Java. Note that because the increment is at the start of the<br />
method, the first print will output the value 1.<br />
Alice and Java Functions<br />
The output from sayHi_param.Java (from Alice)<br />
Next we will compare functions. We saw in week 2 that functions return a value to the<br />
program that it was called from. In Alice we used functions to get information about an object<br />
which might have been the objects height or the distance from another object.<br />
In Java we can use functions to do many tasks for us. for instance as we will see below, to<br />
calculate the area of a square. The following function is shown in both Alice and Java code.<br />
The square area function in Alice<br />
public static int squareArea(int sideLength)<br />
{<br />
int sideSquared;<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\10\for-loops.html<br />
Page 5 of 6<br />
5/05/2008
Chapter 10: Java For Loops<br />
}<br />
sideSquared = sideLength * sideLength;<br />
return(sideSquared);<br />
The output of this method is shown below (from Alice). The full Java code for this method is<br />
downloadable here SquareArea.Java<br />
Co mmon Mistakes<br />
A common mistake in Java is to place the semicolon at the end of the beginning of an for loop,<br />
for example<br />
for ( count = 0; count < 5; count = count + 1 );<br />
{<br />
System.out.println("count = " + count);<br />
}<br />
The semicolon indicates the end of a statement. As a result of this the print startment is not<br />
included within the for loop. This mistake can also happen with while loops.<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\10\for-loops.html<br />
Page 6 of 6<br />
Prev | Up | Next<br />
5/05/2008
Chapter 10: Java Examples<br />
Introduction to Programming<br />
Chapter 10: Java L oops<br />
Ex a mples<br />
Java Examples | Up<br />
Prev | 1 2 p | Next<br />
Scenario: A customer of yours at Square Deal Motors wants a program that will print a square block of stars at the top<br />
of each page. Each block must be 5 stars wide and 5 stars high.<br />
We could solve this by writing a method to print a line of stars the required number wide. The code for this could be:<br />
(download here print5stars.java)<br />
public class print5stars<br />
{<br />
public static void printStars()<br />
{<br />
System.out.println("******");<br />
}<br />
}<br />
public static void main(String[] args) {<br />
printStars();<br />
}<br />
Another way we could print a line of stars is to print one star within a loop. Because we know how many stars we need<br />
to print a for loop is most appropriate for this task. (Download here print5stars_loop.java )<br />
public class print5stars_loop<br />
{<br />
public static void print5StarsLoop()<br />
{<br />
int count;<br />
for(count = 0; count < 5; count = count + 1)<br />
{<br />
/* prints the line of stars - Note print, not println */<br />
System.out.print("*");<br />
}<br />
/* prints a end of line character */<br />
System.out.println();<br />
}<br />
}<br />
public static void main(String[] args)<br />
{<br />
print5StarsLoop();<br />
}<br />
Now that we have printed one line of stars, we need to repeat this line the required number of times. We can<br />
accomplish this by putting the previous for loop inside another for loop. Note that in this case we need two loop<br />
variables; one for the inner loop (this variable counts the number of stars printed per line), and one for the outer loop<br />
(which counts the number of lines printed). (Download the code here printBox.java )<br />
public class printBox<br />
{<br />
public static void print_box()<br />
{<br />
int count_1; /* loop variable for the outer loop */<br />
int count_2; /* loop variable for the inner loop */<br />
for ( count_1 = 0; count_1 < 5; count_1 = count_1 + 1)<br />
{<br />
for ( count_2 = 0; count_2 < 5; count_2 = count_2 + 1)<br />
{<br />
/* prints the line of stars - Note print, not println */<br />
System.out.print("*");<br />
}<br />
/* prints a end of line character */<br />
System.out.println();<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\10\examples.html<br />
Page 1 of 5<br />
5/05/2008
Chapter 10: Java Examples<br />
}<br />
}<br />
Adding Configurability<br />
Scenario: the customer of yours at square deal motors likes the program. But this time they want to be able to print<br />
boxes of different sizes.<br />
We can do this by adding a parameter that sets the width and height of the box to the print_box() method. (download<br />
printBox_Param.java here)<br />
Adding Text Input<br />
}<br />
public static void main(String[] args) {<br />
print_box();<br />
}<br />
public class printBox_Param<br />
{<br />
public static void print_box_param(int size)<br />
{<br />
int count_1;<br />
int count_2;<br />
for ( count_1 = 0; count_1 < size; count_1 = count_1 + 1)<br />
{<br />
for ( count_2 = 0; count_2 < size; count_2 = count_2 + 1)<br />
{<br />
System.out.print("*");<br />
}<br />
System.out.println();<br />
}<br />
}<br />
}<br />
public static void main(String[] args)<br />
{<br />
print_box_param(8);<br />
}<br />
Scenario: Your customer changes their mind again. This time they want to input the size of the box they require. As we<br />
already have a size parameter in the printBox() method, we can use the ConsoleReader to read in the required size<br />
from the user. ( printBox_param_GetSize.java )<br />
public class printBox_param_GetSize<br />
{<br />
public static void print_box_param_get_size(int size)<br />
{<br />
int count_1;<br />
int count_2;<br />
for ( count_1 = 1; count_1
Chapter 10: Java Examples<br />
}<br />
}<br />
boxSize = console.readInt();<br />
print_box_param_get_size(boxSize);<br />
Adding Special Cases<br />
Scenario: The customer likes everything so far, but wants to see what a hollow square would look like.<br />
To only print the stars on the edge rows and columns of the box we must find what the values of count_1 and count_2<br />
are when these stars are printed. For the rows of stars, the loop starts with a value of 1 and ends when the value of<br />
count_1 reaches the value in size. So we can say if the value of count_1 is equal to either 1 , or size, then print a row<br />
of stars. (Note: we must use if( count_1 == 1 || count_1 == size), we cannot just say if(count_1 == 1 ||<br />
size) ).<br />
Likewise, when we are printing a row of stars the loop starts at 1 and ends when the value of count_2 equals size. The<br />
final condition when a star would be printed on an edge of the square is then:<br />
if( count_1 == 1 || count_1 == size || count_2 == 1 || count_2 == size)<br />
When this is true, we print a "*", else we print a space. (Download HollowBox.java here )<br />
public class HollowBox<br />
{<br />
public static void print_box_param_get_size(int size)<br />
{<br />
int count_1;<br />
int count_2;<br />
for ( count_1 = 1; count_1
Chapter 10: Java Examples<br />
The input must be in the range 0 to 100. Let's first make sure the program will only let the user enter marks within the<br />
valid range of values. (This is known as validating the input data.)<br />
We can use a function for this that takes two input parameters; a minimum and a maximum result. In this case, we'll<br />
use 0 for the minimum and 100 for the maximum. Also note in the program that the input is placed inside a loop that<br />
does not exit until the user has entered a valid number; also of note, if the user does enter an invalid number, a<br />
message to tell them of this is displayed and the program then asks for further input. ( ValidNumber.java )<br />
public class ValidNumber<br />
{<br />
public static int Get_ValidNumber(int minimum, int maximum)<br />
{<br />
int number;<br />
ConsoleReader console = new ConsoleReader();<br />
}<br />
/* we need to set number to a value that will be true for the loop test */<br />
/* in this case minimum - 1 is less than minimum and gives us a true from the test */<br />
number = minimum - 1;<br />
while ( number < minimum || number > maximum)<br />
{<br />
System.out.print("Input the students result : ");<br />
number = console.readInt();<br />
if( number < minimum || number > maximum)<br />
{<br />
System.out.println("That result is not in the valid range");<br />
}<br />
}<br />
return(number);<br />
}<br />
public static void main(String[] args)<br />
{<br />
int result;<br />
}<br />
result = Get_ValidNumber(0, 100);<br />
System.out.println("The students result you entered was " + result);<br />
Now that we are sure that the user can only enter valid marks, we can proceed to write code to display the students<br />
grade. For this we will need to use a number of if and if..else statements to allow the corresponding grade to be<br />
displayed. ( StudentGrade.java )<br />
public class StudentGrade<br />
{<br />
public static int Get_ValidNumber(int minimum, int maximum)<br />
{<br />
int number;<br />
ConsoleReader console = new ConsoleReader();<br />
/* we need to set number to a value that will be true for the loop test */<br />
/* in this case minimum - 1 is less than minimum and gives us a true from the test */<br />
number = minimum - 1;<br />
while ( number < minimum || number > maximum)<br />
{<br />
System.out.print("Input the students result : ");<br />
number = console.readInt();<br />
if( number < minimum || number > maximum)<br />
{<br />
System.out.println("That result is not in the valid range");<br />
}<br />
}<br />
return(number);<br />
}<br />
public static void main(String[] args)<br />
{<br />
int result;<br />
result = Get_ValidNumber(0, 100);<br />
System.out.println("The students result you entered was " + result);<br />
System.out.print("This corresponds to a grade of ");<br />
/* if result is less than or equalto 100 and result greater than or equal to 80 */<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\10\examples.html<br />
Page 4 of 5<br />
5/05/2008
Chapter 10: Java Examples<br />
}<br />
}<br />
if((result = 80))<br />
{<br />
System.out.println("High Distinction");<br />
}<br />
else if((result < 80) && (result >= 70))<br />
{<br />
System.out.println("Distinction");<br />
}<br />
else if((result < 70) && (result >= 60))<br />
{<br />
System.out.println("Credit");<br />
}<br />
else if((result < 60) && (result >= 50))<br />
{<br />
System.out.println("Pass");<br />
}<br />
else if((result < 50) && (result >= 0))<br />
{<br />
System.out.println("Fail");<br />
}<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\10\examples.html<br />
Page 5 of 5<br />
Prev | Up | Next<br />
5/05/2008
Practical 10<br />
Introduction to Programming<br />
Chapter 10: Java Loops and Methods<br />
Practical Exercises<br />
Aim: To investigate Java IF statements.<br />
public class tax<br />
{<br />
public static void main(String[] args)<br />
{<br />
int num;<br />
ConsoleReader console = new ConsoleReader();<br />
System.out.print("Please enter an integer : ");<br />
num = console.readInt();<br />
System.out.println("The number you entered was : " + num);<br />
}<br />
}<br />
Practical Exercises | Up<br />
Prev | 1 2 p | Next<br />
Using the above java program as a template complete the following tasks (you can download<br />
the code here tax.java you will also need ConsoleReader.java this must be included in the<br />
same directory as your source code)<br />
Q1 A customer has asked you to write a tax program. The program should accept an integer<br />
value (the amount of earnings) and calculate how much income is <strong>subject</strong> to tax.<br />
Incomes of less than or equal to $6000 attract no tax. Incomes over $6000 pay tax only on<br />
the amount over the tax-free threshold. For example, $7000 only attracts tax on $1000.<br />
Two sample runs of the program are shown below (user input is shown underlined ):<br />
run 1:<br />
Please enter your earnings : 4000<br />
Your income was : 4000<br />
You pay no tax<br />
run 2:<br />
Please enter your earnings : 100000<br />
Your income was : 100000<br />
You pay tax on 94000<br />
Write an algorithm (i.e. storyboard) for producing the above program. Don't forget to<br />
consider what variables are required.<br />
Try converting the algorithm into a Java program.<br />
Page 1 of 2<br />
Q2 Alter the program so it now asks for the user's age, and only performs the tax calculation<br />
if the user is between (inclusive) 18 and 65.<br />
Q3 Write an algorithm (i.e. storyboard) for reading 2 integers, A and B. The algorithm prints<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\10\practical.html<br />
5/05/2008
Practical 10<br />
out whether A equals B, or is less than or greater than B. Convert your algorithm into a Java<br />
program.<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\10\practical.html<br />
Page 2 of 2<br />
Prev | Up | Next<br />
5/05/2008
Chapter 11: Arrays<br />
Introduction to Programming<br />
Chapter 11: Arrays<br />
At the completion of this weeks study students should.<br />
Understand the basics of single dimension arrays<br />
Co urse Materials<br />
Online Course Material<br />
Please select a subtopic to view its contents.<br />
Arrays in Alice and Java<br />
Practical Exercises<br />
Practical Exercises<br />
Additional Materials<br />
There are no additional <strong>material</strong>s available at this time.<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\11\index.html<br />
Page 1 of 1<br />
Arrays | Up<br />
Prev | 1 p | Next<br />
Prev | Up | Next<br />
14/05/2008
Chapter 11: Arrays in Alice and Java<br />
Introduction to Programming<br />
Chapte r 11 : Arrays<br />
Arr ays i n Alice a nd Ja va<br />
Arrays in Alice and Java | Up<br />
Prev | 1 p | Next<br />
Up until now, all the variables we have been using refer to a single thing (or piece of information); for example, one integer, or one<br />
object. We can change the value in the variable, but at any one time a variable can only hold one value. There may be times when we<br />
need to refer to groups of the same type, such as a set of numbers, or a collection of objects. If we needed to remember the results of<br />
a group of students we could have a number variable for each student.<br />
eg. StudentResults01, StudentResults02, StudentResults03, (and so on)<br />
This is manageable if the class was small, but what about if there were hundreds (or more) students in the class...<br />
StudentResults1000? (!) This kind of technique would end up completely unmanageable and impractical. Alice, and most other<br />
programming languages, have a structured variable called an array. These can be used to store a group of any particular variable type.<br />
When we are using this group variable (array) we give it a single name; in this case we'll call it StudentResults and define that there<br />
are 10 students in the class.<br />
Retrieving Array Values<br />
When we are accessing variables in an array, we use the array's index. (In this example, we'll refer to students by their index.) The<br />
indices start at 0 (the first element of the array), and the last is 9 (the final element).<br />
For example, if we had the results for 3 of our students (student number 3 has a mark of 80, student number 5 has a mark of 55 and<br />
student number 8 has a mark of 45) we could say "set StudentResults index 3 to 80, StudentResults index 5 to 55, and set<br />
StudentResults index 8 to 14"<br />
Arrays in Summary<br />
An array allows us to conveniently group together a series of variables.<br />
To access a element within an array we use the array's name and the index of the element you need.<br />
Arrays have one restriction. All the elements must be of the same type. eg. All numbers, all strings or all objects. The variable<br />
type within an array cannot be mixed.<br />
Arr ays i n Alice<br />
An array's indices always start at 0.<br />
A collection (array) of 10 number variables<br />
The indices in the student_results array<br />
Using the index number to access an element in the array<br />
Page 1 of 6<br />
Alice provides us with an ArrayVisualisation tool. This is located in the 'visualizations' objects in the object gallery. Note: the Array<br />
Visualisation tool can only be used with objects.<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\11\arrays.html<br />
14/05/2008
Chapter 11: Arrays in Alice and Java<br />
The Array Visualisation object<br />
To use this tool, we first need to add to the world, the objects we wish to visualise. Once we have done thi,s we can add the array<br />
visualisation tool into the world. Once this is done, the visualisation object will prompt to add objects to the array.<br />
The array visualisation object will prompt you to add<br />
objects to the array<br />
Once you have finished adding the objects to the array visualisation click on 'OK'; the objects you have previously placed in the world<br />
have now moved to the visualisation object.<br />
An array of objects using the visualisation tool<br />
Page 2 of 6<br />
We can now use the index to access a particular object. For instance, if we needed to make the chicken jump into the air: with the<br />
chicken at index 1, we would say, "the value at ArrayVisualization[1] move up .5 meter." This would make the object in that element<br />
(the chicken) move up .5 meter.<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\11\arrays.html<br />
14/05/2008
Chapter 11: Arrays in Alice and Java<br />
Accessing Each Element (Traversing) an Array<br />
Quite often, we need to step through an array and access each element in turn. We have used loops before in Alice to repeat an action.<br />
In this instance, because we know the number of times we need to repeat the loop, a 'counted loop' is the best choice. We start the<br />
loop at 0, and continue counting up to, but not including, the number of elements in the array. Because we have three objects in the<br />
visualisation, the loop will then be "loop index from 0 up to (but not including) 3 incrementing by 1". This will produce the following<br />
actions.<br />
Swapping Two Objects in an Array<br />
In week 7, we looked at swapping two variables about, with the use of a temporary variable to store intermediate data. This technique<br />
can also be applied to arrays. In the 'visualizations' object list is a variable visualisation tool that allows us to store a single object.<br />
Using an array of two objects and the variable visualisation tool, we are able to swap -- and watch -- the two objects in the same way<br />
we did with variables.<br />
Move the object in ArrayVisualisation [0] to the VariableVisualisation<br />
Move the object in ArrayVisualisation [1] to ArrayVisualisation [0]<br />
Move the object in VariableVisualisation to ArrayVisualisation [1], completing the swap<br />
This is demonstrated in the animation below.<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\11\arrays.html<br />
The value at ArrayVisualization [ 1 ] move up .25 meter<br />
Using a 'counted loop' to step through the elements of an array<br />
Page 3 of 6<br />
14/05/2008
Chapter 11: Arrays in Alice and Java<br />
Accessing a Property of an Array Object<br />
To access a property of an array object (in this example, an object's height), we first need to drop in the height function, such as:<br />
Once this has been done, we can then drop in the array position that we're interested in. For example, for the second animal in the<br />
array:<br />
Iterating Through the Array in Reverse<br />
There are times when we may need to loop through the array elements in reverse. This can be accomplished by manipulating the loop<br />
numbers so that when they are used to specify an array element, they will be counting down instead of up.<br />
For example, if there are three elements in an array, we can use a loop "loop index from 0 up to (but not including) 3 times<br />
incrementing by 1". We're still not counting down yet, though! To do this, we access element at (2 - index) within the loop. When index<br />
is 0, 2 - 0 is 2 so we would be accessing element 2. The Alice code for this is shown below.<br />
Problems With Arrays<br />
Swapping two objects in an array using a temporary variable<br />
The first step to access an array object's height<br />
Accessing the required element in the array<br />
Looping through an array in reverse<br />
We must be very careful when using a loop to step through an array, that we don't accidentally run off the end. The loop must only<br />
access the number of elements that have been created. For example; for a three element array, the limit of the loop must be "up to<br />
(but not including) 3". This will stop the loop counter before it is trying to access an element that is off the end of the array. The<br />
example below shows what happens with a three element array when we have set the limit too high.<br />
The effect of setting the loop limit to high<br />
This causes a runtime error. (A runtime error is one that will only occur when the program is run.)<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\11\arrays.html<br />
Page 4 of 6<br />
14/05/2008
Chapter 11: Arrays in Alice and Java<br />
Using an Array in an If Statement<br />
We can use the index value of an array to test an individual element. In the above example, we are using a variable which has been set<br />
to 2 (the index of the array element we wish to test). We can then use the element variable to test if the height of the animal at that<br />
index is less than 9. We can also put the if statement in a loop that will test the height of all animals in the array.<br />
Arr ays i n J av a<br />
We have seen previously that we can use an array visualisation object in Alice to manipulate the objects within an array. Java also<br />
allows us to do the same. Within Alice, an array could only contain one type of object. On the other hand, Java allows us to create<br />
arrays that can contain many different types of objects.<br />
Note: with Alice, an array can only hold one type of item -- this rule also applies to Java. When we create an array in Java, we first<br />
need to tell the program what type the items will be; then we need to specify how many items there are.<br />
We can now add numbers to the array. In Java we use the array index; exactly the same as in Alice. To place the number 411 in the<br />
second array element we would use:<br />
Let's have a look at a program in Java that uses an array to add together a series of numbers.<br />
First, we need to define the array type and name.<br />
Then we need to specify the number of elements in the array.<br />
The error message from the previous code<br />
An array element used in an if statement caption here<br />
An if statement placed within a loop<br />
int numGroup[]; /* tells java that the array will contain numbers<br />
and will be called numGroup */<br />
numGroup = new int[3]; /* tells java that the array will have three elements */<br />
numGroup[1] = 411;<br />
As with Alice, arrays in Java start at index 0.<br />
Two other variables are defined; total (holds the total of the numbers in the array) and index (the loop counter).<br />
We have seen before how to put numbers into an array; this is done to the three elements of the array.<br />
The next line total = 0; sets total to a known value before we enter the loop.<br />
This is important as within the loop we are adding to the value that is already in total (total = total + ...) This is<br />
saying add a value to total, and place the result back into total.<br />
Page 5 of 6<br />
What if total already contained a value before we entered the loop? We would be adding to the value that was previously<br />
in total, and the final result would be wrong. Within the loop, the loop counter is used to access the value in each array<br />
element and add this value to the value in total.<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\11\arrays.html<br />
14/05/2008
Chapter 11: Arrays in Alice and Java<br />
The Java program can be downloaded here JavaArray.java<br />
public class JavaArray<br />
{<br />
public static void main(String[] args)<br />
{<br />
int numGroup[]; /* define the array type and name */<br />
numGroup = new int[3]; /* define the number of elements in the array */<br />
int total;<br />
int index;<br />
}<br />
}<br />
numGroup[0] = 10;<br />
numGroup[1] = 20;<br />
numGroup[2] = 30;<br />
total = 0; /* total is set to a known start value, because we are adding to it within the loop */<br />
for ( index = 0; index < 3; index = index + 1 )<br />
{<br />
total = total + numGroup[index]; /* using the loop counter to access each element within the array */<br />
}<br />
System.out.println("The total of the numbers in numGroup array is " + total);<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\11\arrays.html<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
Page 6 of 6<br />
Prev | Up | Next<br />
14/05/2008
Practical 11<br />
Introduction to Programming<br />
Chapter 11: Arrays<br />
Practical Exercises<br />
Aim: To investigate arrays in Java.<br />
Q1. What is the error in the following code fragment?<br />
int count;<br />
int data[10];<br />
for (count = 0; count
Practical 11<br />
For example, "Student 0 received a result of 75 this is a Distinction"<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\11\practical.html<br />
Page 2 of 2<br />
Prev | Up | Next<br />
14/05/2008
Chapter 12: 2D Arrays<br />
Introduction to Programming<br />
Chapter 12: 2D Arrays<br />
At the completion of this weeks study students will have<br />
An understanding of the basics of two dimensional arrays in Java<br />
Co urse Materials<br />
Online Course Material<br />
Please select a subtopic to view its contents.<br />
2 Dimensional Arrays in Java<br />
Practical Exercises<br />
Practical Exercises<br />
Additional Materials<br />
There are no additional <strong>material</strong>s available at this time.<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\12\index.html<br />
Page 1 of 1<br />
Up | Site Map<br />
Up | Site Map<br />
9/05/2008
Chapter 12: 2D Arrays in Java<br />
Introduction to Programming<br />
Chapter 12: 2 Di mensional Arrays<br />
2 Dimensional Arra ys in Java<br />
Up | Site Map<br />
In last weeks <strong>material</strong> we looked at single dimensional arrays. We found that to access a element (room) in a single<br />
dimensional array we needed to use a single index value. For example StudentResults[5]. We also learnt an important<br />
rule with all arrays, that is that each element of the array must be of the same type - eg. all ints, or all strings or all<br />
objects as in Alice. With two dimensional arrays we can think of them as an array with each element being an array in<br />
itself. In last weeks <strong>material</strong> the example was of an single dinensional array of 10 studentResults.<br />
A single dimensional array of 10 students.<br />
What if our array 'Class room' had not one row of desks but many each row having the same number of 'desks' each<br />
'desk' having one student. If we had an array 'class room' with 4 'Rows of desks' and each 'row having four desks in it,<br />
it would look like this :<br />
A 2 dimensional array of four elements by four elements<br />
Page 1 of 4<br />
We have seen before that all elements of an array must be of the same type, let's now assume that the array is to<br />
store the exam results of each of the students in the 'Class room'. Each element in the array is an integer.<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\12\2d-arrays-java.html<br />
9/05/2008
Chapter 12: 2D Arrays in Java<br />
As with single dimensional arrays the name of a two dimensional array is the name of the whole array.<br />
Arrays in Java<br />
A four by four array of integers<br />
The name of a two dimensional array is the name of the whole array<br />
In last weeks examples we used a single index value to access an individual element in the array. With two<br />
dimensional arrays we need to use two index values one for the row number in the array and another for the column<br />
number. Say we needed to store the exam results of 16 students but we wanted to store the data simmilar to the<br />
positions they sat in class. We all ready had the exam results of 3 of the students that we needed to place at the<br />
position in the array that corresponded to their seating position in class, eg. if the student at desk, row 2 coulmn 1<br />
had a result of 55 and the student at desk row 0 column 2 had a result of 78 and the student next to them at row 0<br />
column 3 had the same result. the java code to put the values into the array would be<br />
public class Array2_1<br />
{<br />
public static void main(String[] args)<br />
{<br />
int StudentResults[][]; // defines a 2 dimensional array of ints called StudentResults<br />
StudentResults = new int[4][4]; // Sets the size of the array to 4 elements * 4 elements<br />
}<br />
}<br />
StudentResults[2][1] = 55;<br />
StudentResults[0][2] = 78;<br />
StudentResults[0][3] = 78;<br />
Let's try this again this time inputting the results from the keyboard. In this example there are two loops. the value of<br />
the outer loop (row) is used to index each row of the array. Likewise the value of the inner loop (column) is used to<br />
index each column in the array. The first time through the outer loop the value in row will be 0, while the value in row<br />
remains 0 the inner loop value in column will step from 0 to 3.<br />
The value in the<br />
outer (row) loop is<br />
The value in the inner<br />
loop (column) is<br />
The array element we are<br />
looking at in StudentResults is<br />
0 0 StudentResults[0][0]<br />
0 1 StudentResults[0][1]<br />
0 2 StudentResults[0][2]<br />
0 3 StudentResults[0][3]<br />
1 0 StudentResults[1][0]<br />
1 1 StudentResults[1][1]<br />
1 2 StudentResults[1][2]<br />
1 3 StudentResults[1][3]<br />
2 0 StudentResults[2][0]<br />
2 1 StudentResults[2][1]<br />
2 2 StudentResults[2][2]<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\12\2d-arrays-java.html<br />
Page 2 of 4<br />
9/05/2008
Chapter 12: 2D Arrays in Java<br />
2 3 StudentResults[2][3]<br />
3 0 StudentResults[3][0]<br />
3 1 StudentResults[3][1]<br />
3 2 StudentResults[3][2]<br />
3 3 StudentResults[3][3]<br />
public class Array2_2<br />
{<br />
public static void main(String[] args)<br />
{<br />
int row;<br />
int column;<br />
int StudentResults[][];<br />
StudentResults = new int[4][4];<br />
ConsoleReader console = new ConsoleReader();<br />
}<br />
}<br />
for (row = 0; row < 4; row = row + 1) // The outer loop indexes each row in the array<br />
{<br />
for ( column = 0; column < 4; column++ ) // inner loop steps through each column<br />
{<br />
System.out.print("Please enter score for student at row " + row);<br />
System.out.print(" ,column " + column + " : ");<br />
StudentResults[row][column] = console.readInt();<br />
}<br />
}<br />
The above example uses nested loops to access each row (this is done by the outer loop) and column (done by the<br />
inner loop). We can then use the loop values as the index values in the readInt statement, this reads the value from<br />
the user direct to the StudentResults array at the element indexed by the row and column variables.<br />
Lets now extend the previous program and print out the results (we'll take it that if a student has a result of zero their<br />
mark has not been entered and should not be printed).<br />
public class Array2_3<br />
{<br />
public static void main(String[] args)<br />
{<br />
int row;<br />
int column;<br />
int StudentResults[][];<br />
StudentResults = new int[4][4];<br />
ConsoleReader console = new ConsoleReader();<br />
Page 3 of 4<br />
for (row = 0; row < 4; row = row + 1)<br />
{<br />
for ( column = 0; column < 4; column++ )<br />
{<br />
System.out.print("Please enter score for student at row " + row);<br />
System.out.print(" ,column " + column + " : ");<br />
// we need to enter a valid number here to avoid an error.<br />
StudentResults[row][column] = console.readInt();<br />
}<br />
}<br />
for (row = 0; row < 4; row = row + 1)<br />
{<br />
for ( column = 0; column < 4; column++ )<br />
{<br />
if(StudentResults[row][column] > 0) // if a result has been entered<br />
{<br />
System.out.print("The student at row " + row);<br />
System.out.print(" ,column " + column);<br />
System.out.println(" recieved a mark of : " + StudentResults[row][column]);<br />
}<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\12\2d-arrays-java.html<br />
9/05/2008
Chapter 12: 2D Arrays in Java<br />
}<br />
}<br />
}<br />
}<br />
We can also use the nested loops to do operations on rows of the array. In this example we get the average mark for<br />
each row, an also an overall average for the 'Classroom'<br />
public class Array2_4<br />
{<br />
public static void main(String[] args)<br />
{<br />
int row;<br />
int column;<br />
int row_total;<br />
int overall_total;<br />
int StudentResults[][];<br />
StudentResults = new int[4][4];<br />
ConsoleReader console = new ConsoleReader();<br />
}<br />
}<br />
// Input values into the 2 dimensional array<br />
for (row = 0; row < 4; row = row + 1)<br />
{<br />
for ( column = 0; column < 4; column++ )<br />
{<br />
System.out.print("Please enter score for student at row " + row);<br />
System.out.print(" ,column " + column + " : ");<br />
// we need to enter a valid number here to avoid an error.<br />
StudentResults[row][column] = console.readInt();<br />
}<br />
}<br />
System.out.println("Printing the average mark for each row of students : ");<br />
overall_total = 0; // set overall_total to 0 before starting calculations.<br />
for (row = 0; row < 4; row = row + 1)<br />
{<br />
System.out.print("Row " + row + " : ");<br />
row_total = 0; // reset row_total to 0 to start calculations for the new row<br />
for ( column = 0; column < 4; column++ )<br />
{<br />
row_total = row_total + StudentResults[row][column];<br />
overall_total = overall_total + StudentResults[row][column];<br />
}<br />
System.out.println(row_total / 4); // divided by the number of students in the row<br />
}<br />
System.out.println("The overall average is : " + (overall_total / ( 4 * 4 )));<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\12\2d-arrays-java.html<br />
Page 4 of 4<br />
Up | Site Map<br />
9/05/2008
Practical 12<br />
Introduction to Programming<br />
Chapte r 12 : 2 D Arra ys<br />
Pra c ti c al E xe rcises<br />
1. The following code prints out a box of numbers eg.<br />
1 2 3<br />
4 5 6<br />
7 8 9<br />
public class NumberBox<br />
{<br />
public static void main(String[] args)<br />
{<br />
int row;<br />
int column;<br />
int count;<br />
int NumberBox[][];<br />
NumberBox = new int[3][3];<br />
}<br />
}<br />
// put the numbers into the 2D array<br />
count = 1;<br />
for ( row = 0; row < 3; row = row + 1)<br />
{<br />
for ( column = 0; column < 3; column = column + 1)<br />
{<br />
NumberBox[row][column] = count;<br />
count = count + 1;<br />
}<br />
}<br />
// Print out the reversed box<br />
for ( row = 0; row < 3; row = row + 1)<br />
{<br />
for ( column = 0; column < 3; column = column + 1)<br />
{<br />
System.out.print(" " + NumberBox[row][column]);<br />
}<br />
System.out.println();<br />
}<br />
// your code goes in here<br />
for ( row = 0; row < 3; row = row + 1)<br />
{<br />
for ( column = 0; column < 3; column = column + 1)<br />
{<br />
System.out.print(" " + NumberBox[row][column]);<br />
}<br />
System.out.println();<br />
}<br />
your task is to modify the code so that the second time the code is printed the result is swaped from left to right<br />
3 2 1<br />
6 5 4<br />
9 8 7<br />
© 2008 <strong>RMIT</strong> <strong>University</strong> - Copyright Information - Disclaimer - Site Map<br />
Page 1 of 1<br />
Up | Site Map<br />
2. modify the above code so that the second time the array isprinted the output is mirrored left to right and<br />
top to bottom eg.<br />
9 8 7<br />
6 5 4<br />
3 2 1<br />
<strong>file</strong>://Z:\contribute\cpt120\chapter\12\practical.html<br />
Up | Site Map<br />
9/05/2008