Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
1001ICT Introduction To Programming
Lecture Notes
School of Information and Communication Technology
Griffith University
Semester 2, 2015
1
1 Introduction
Welcome to 1001ICT Introduction To Programming (ITP)and 7001ICT Pro-
gramming Principles 1 (PP1).
These lecture notes are divided into sections. This one describes the course’s:
• content;
• roles and responsibilities;
• assessment;
• resources; and
• some things you need to do now.
1001ICT Introduction To Programming – 2015-2 2
This course is being offered in parallel at the:
• Logan campus; and
• Nathan campus.
It is the same course on both campuses, just different lecturers.
1001ICT Introduction To Programming – 2015-2 3
1.1 7001ICT Programming Principles 1
For this semester, the class also includes Masters students enrolled in 7001ICT
PP1.
The course materials and assessment items will be the same as for the un-
dergraduate course, however the grading basis will be different.
Please note that this is an introduction to programming.
If your undergraduate program included programming, please see the course
convenor or your program convenor for advice as to whether this is the right
course for you.
1001ICT Introduction To Programming – 2015-2 4
1.2 What to do in lectures
1.2.1 Why have lectures?
• They are an efficient way to convey the content of a course.
• The meaning of the content is conveyed better verbally than just in a
written form as:
– It’s less boring than just reading.
– Some things are hard to read by yourself at first (programs,
maths, diagrams).
– It’s easier to tell what’s important from the emphasis given.
– You can ask questions.
– It’s more social.
1001ICT Introduction To Programming – 2015-2 5
• It’s regular time set aside for thinking about the course.
• It’s the best place for important announcements.
• It’s an opportunity for feedback about how the course is going and
how the class is performing.
It’s harder to keep up in a course if you are missing lectures.
1001ICT Introduction To Programming – 2015-2 6
1.2.2 Take notes?
These notes are posted on the web.
So you don’t have to copy them all down.
But we say more than goes in the slides.
You should be prepared to take notes that capture the extra information.
Lecture notes are available on the web before the lecture, so bring a printout,
so you can add extra highlighting or comments.
1.2.3 Take notes today!
Write down the things in colour.
1001ICT Introduction To Programming – 2015-2 7
1.3 Course Convenors & Lecturers
Logan lecturer Ali Zia
ali.zia@griffithuni.edu.au
Nathan lecturer Andrew Rock
& course convenor a.rock@griffith.edu.au
Technology Building (N44) 1.37
1001ICT Introduction To Programming – 2015-2 8
1.4 Course web site
These notes will be posted on the web at:
http://www.ict.griffith.edu.au/arock/itp/
You will find the laboratory notes and anything else you need there too.
Write down the uniform resource locator (URL) now!
You can also access these resources via Learning@Griffith, though direct
access via the above URL will be quicker.
Nathan lectures are captured and available, after editing, on
Learning@Griffith’s Echocentre.
1001ICT Introduction To Programming – 2015-2 9
1.5 What the course is about
This is an introduction to:
• programming tools;
• programming concepts;
• problem solving; and
• programming languages.
A lot of the programs we will write will be for robots.
Others will be for personal computers, with text or graphical output.
We will be learning and programming in a subset of the Java programming
language.
1001ICT Introduction To Programming – 2015-2 10
1.6 Why learn programming
The applications we use, the internet, games, entire businesses are made up
of programs, and someone has written them.
The ability to create programs is important if you want to participate in
building the future.
The understanding of what can and can’t be achieved with a program is
important, even if you don’t write programs yourself. People are needed to
design, document and specify programs, as well as code them.
Multimedia students should particularly consider programming experience
as their edge over competitors doing ordinary design courses.
1001ICT Introduction To Programming – 2015-2 11
Many courses will tell you that they will help you develop problem solving
skills. (Employers like it. “Don’t come to me with problems. Come to me
with solutions!”)
But a program is usually not the specific solution to one instance of a prob-
lem, it is the solution to a whole class of problems, written out clearly. That
is a higher level of problem solving.
Programming is one of those things that is satisfying, enjoyable and reward-
ing “... not because they are easy, but because they are hard...” (JFK).
1001ICT Introduction To Programming – 2015-2 12
1.7 The choice of programming languages
In your working life you will write lots of programs, in lots of programming
languages.
Any time you create a script, automation, spreadsheet, or animation, it’s
programming.
It may be that you never program in Java after completion of your program-
ming classes.
However, Java is a programming language that has all of the attributes found
in all of the common application and scripting languages. Its notation is
similar to many, including C, C++, C#, JavaScript, and ActionScript.
1001ICT Introduction To Programming – 2015-2 13
1.8 Can you learn programming?
Yes!
Easy: Convincing us you are capable of programming if you try. We already
believe it.
Hard: Convincing yourself.
Come to classes. Pay attention. Don’t panic. Persevere. Ask questions.
You will pass this course.
1001ICT Introduction To Programming – 2015-2 14
1.9 Classes and assessment
1.9.1 Lectures
In a 2-hour lecture every week, we will learn the concepts and strategies
used in programming.
During 5 of the lectures, we will test your learning with quizzes.
3 + 4 + 5 + 6 + 7 = 25 marks
1.9.2 Workshops
In a 1-hour workshop every week we demonstrate more examples and pro-
vide and discuss extra non-assessed problems.
1001ICT Introduction To Programming – 2015-2 15
1.9.3 Labs
In 10 2-hour assessed lab classes you put the theory into practice.
2 + 2 + 3 + 3 + 4 + 4 + 5 + 5 + 6 + 6 = 40 marks
1.9.4 Common times
A common time (we call them a “drop-in”) is a class where there are no set
activities, but you can get individual help if you need it or we can challenge
you with extra, harder problems if you want them.
1.9.5 Final project
The course ends with a larger programming project (35 marks).
1001ICT Introduction To Programming – 2015-2 16
1.9.6 Attendance summary
Students are expected to attend all lectures and workshops.
You are enrolled in one 2 hour labs class. Attend that every week from week
2.
Attend any common time as needed, from week 2.
“Eighty percent of success is showing up.” – Woody Allen.
1.9.7 Assessment summary
quizzes 3 + 4 + 5 + 6 + 7 = 25
labs 2 + 2 + 3 + 3 + 4 + 4 + 5 + 5 + 6 + 6 = 40
project 35
total 100
1001ICT Introduction To Programming – 2015-2 17
1.9.8 Minimum requirements for labs and quizzes
The labs are quizzes are treated as one assessment item each.
If you do not attend the majority of each, we don’t think you are really
attempting them.
If you don’t attend at least 6 labs, you don’t get any lab marks at all.
If you don’t attend at least 3 quizzes, you don’t get any quiz marks at all.
Either of these outcomes will make it almost impossible to pass the course.
You may even be awarded a grade of Fail Not Sat, which would be a better
indication of your performance than a plain Fail.
1001ICT Introduction To Programming – 2015-2 18
1.9.9 Supplementary exam
Supplementary assessment, if passed, can raise your grade from a 3 to the
lowest passing grade (a 4).
To be eligible, you must have been awarded a 3, have submitted/sat the
majority of the assessed labs, the majority of the quizzes, and at least part
of the final project.
For this course, the supplementary assessment takes the form of a two-hour,
closed-book, written examination.
1001ICT Introduction To Programming – 2015-2 19
1.10 Lecture notes
The lecture notes are available on the course web site in various formats.
The most useful format is the A5 version, which:
• has a table of contents;
• has a glossary and an index;
• has clickable links;
• includes appendices that summarise the programming language and
environments, plus other useful reference information;
• is ideally formatted for a tablet or laptop screen; and
• prints double-sided as a small book.
1001ICT Introduction To Programming – 2015-2 20
1.11 Griffith Sciences Laboratory Induction
You will have been briefed in orientation about workplace health and safety,
and the on-line course and test on Learning@Griffith in the organisation
Griffith Sciences Laboratory Induction that you must complete.
In this course we will be checking that you have passed that test.
You must print the certificate that shows that you passed that test, within the
last year, and bring it to your first programming lab class (in week 2).
1001ICT Introduction To Programming – 2015-2 21
1.12 Peer Assisted Study Sessions
This course has available a student learning support service, Peer Assisted
Study Sessions (PASS).
PASS offers free extra weekly study sessions, led by more experienced fel-
low students (PASS leaders).
The details about PASS will be presented by the PASS leaders in the week
1 lecture.
PASS is optional (and limited access), but students who use it have been
shown to get better results than students who don’t.
1001ICT Introduction To Programming – 2015-2 22
1.13 Laboratory 1
The first lab will be held in week 2.
The exercise notes are on the course web site.
We will find and preview them now.
We will also find the Griffith Sciences Laboratory Induction on
Learning@Griffith.
1001ICT Introduction To Programming – 2015-2 23
1.14 Section summary
This section covered:
• what happens in lectures;
• why this course on programming is an important part of your program
of studies;
• how this course is organised, taught and assessed;
• where the resources for this course can be found on the web;
• who the teachers are and how to contact them; and
• what you need to do to get started in this course.
1001ICT Introduction To Programming – 2015-2 24
1.15 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 25
1.16 Things to do
What you need to be doing as soon as possible to get started:
• Get a diary or organiser and plan how you can spend your week prof-
itably, including the following items.
• Make sure you are properly enrolled in this course and in a laboratory.
• Read the course outline and the course web site.
• Prepare for laboratory 1, in week 2. Find the notes on the web site.
There are some questions you need to answer before your lab class.
• Complete the Griffith Sciences Laboratory Induction on
Learning@Griffith, and bring the printed certificate to labs at least
once.
1001ICT Introduction To Programming – 2015-2 26
• Lecture notes appendices A through G contain useful information that
you should read now.
• Prepare for the first workshop (in week 2) by reading the exercises on
the web site when they are released.
1001ICT Introduction To Programming – 2015-2 27
2 Elements of Java
Java is a popular, modern, third generation language, suited to a wide range
of applications and environments.
Specifically:
• It supports large-scale software engineering, with good control of en-
capsulation and namespaces.
• It supports high-quality secure coding. The compiler enforces and
supports a lot of good practices.
These things are important for professional programmers, but can get in the
way of learning the basics in an introductory course like this.
1001ICT Introduction To Programming – 2015-2 28
2.1 The basics
Java has these elements common to all third generation programming lan-
guages (in the order that they are easiest to learn):
• statements;
• variables;
• simple data types;
• control structures;
• encapsulation at the methods/functions/procedures level; and
• arrays.
These will be the elements we will focus on in ITP.
1001ICT Introduction To Programming – 2015-2 29
2.2 Advanced topics
Java has these elements common to most object oriented programming lan-
guages:
• encapsulation at the the classes and objects level;
• exceptions;
• multi-threaded programming;
• event handling; and
• huge libraries and support for programming on all kinds of platforms.
These will be the elements we will focus on in 1005ICT object oriented
programming (OOP) and later courses.
1001ICT Introduction To Programming – 2015-2 30
2.3 Adaptation of Java to teaching
A requirement of a good programming language for learning and teaching
is that it be restrictable.
That is, you should be able to use just a small subset of the language and
get simple things done.
Java does not have this property.
1001ICT Introduction To Programming – 2015-2 31
Consider the very simple task of printing “Hello, World!” on the screen.
To do it you need all of these elements:
• statements;
• variables;
• simple data types;
• encapsulation at the methods/functions/procedures levels;
• arrays; and
• encapsulation at the the classes and objects level.
1001ICT Introduction To Programming – 2015-2 32
This is the simplest Java program for doing the job.
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
If any part is missing, the Java compiler will not accept it.
It can not be fully understood without understanding: classes, objects, meth-
ods, variables, and arrays.
1001ICT Introduction To Programming – 2015-2 33
All textbooks and teachers recognise this problem.
All take different approaches to solving it:
• “Don’t understand it. Just copy it.” (It’s magic!)
• Use another language that’s simpler (but not used in industry).
• Try to teach all the concepts at once.
This course takes this approach:
If the compiler won’t accept subsets of the language so that you
can learn it in easy stages, change the compiler!
1001ICT Introduction To Programming – 2015-2 34
Everything you will learn in this course is Java.
You will not have to unlearn anything as you progress through this course
and to the next.
But you will be able to learn Java in easy stages.
A custom compiler has been developed for this course that implements the
restricted subsets that will support learning Java in these stages:
1. statements (simple types, variables, using an environment)
2. control (loops and selections)
3. methods (encapsulation at the methods level)
4. arrays
The next stage would be to add objects, and that’s full Java.
1001ICT Introduction To Programming – 2015-2 35
2.4 MaSH
The Making Stuff Happen (MaSH) system has been developed for this
course.
It includes the custom compiler.
It is designed to provide a variety of programming environments, for robots
and more.
To write a compiler, one must formally specify the language.
So for the Java language subsets we will use, we have prepared complete
and formal specifications.
You will be able to learn the language from these specifications more easily
than (as is usual) by examples only.
Equal attention has been paid to documenting the programming environ-
ments.
1001ICT Introduction To Programming – 2015-2 36
2.5 Section summary
This section covered:
• What the basic elements of Java that we will teach in this course are.
• What the more advanced elements of Java that we will teach in later
courses are.
• That Java is not restrictable.
• How we will make Java restrictable using MaSH.
1001ICT Introduction To Programming – 2015-2 37
2.6 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 38
3 A First MaSH Program
In this section we will describe a very simple MaSH program and show how
to compile and run it.
Recall this simple Java program.
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Only the blue bit actually makes stuff happen.
1001ICT Introduction To Programming – 2015-2 39
Here is the simplest MaSH program that does the same thing.
import console;
println("Hello, World!");
The blue bit stays exactly the same.
All of the stuff that is about encapsulation is gone.
The red bit has been added.
We will now show how to run it and explain every part of it.
1001ICT Introduction To Programming – 2015-2 40
3.1 How to run a console MaSH program
A console program is one that inputs and outputs only plain text and runs in
a command line (or console) environment, such as: the Command Prompt
on Windows; or the Terminal or xterm on Mac OS X, Unix or Linux.
Example console programs are the MaSH and Java compilers.
A compiler is a program that reads a high level programming language and
translates it into some other (usually lower level) programming language.
See appendix A of the lecture notes for an explanation of the way the
following command examples are displayed.
1001ICT Introduction To Programming – 2015-2 41
3.1.1 Step 1: Create the program file
Use your favourite text editor to create a text containing the text of the
program.
The file must have a name that ends with the filename extension .mash.
The file name must start with an upper case letter.
The rest of the file name must consist only of letters, digits and underscores
(_).
Our example program might be saved in a file named Hello.mash.
Also good: Hello_2_You.mash.
Bad: Hello, World!.mash.
1001ICT Introduction To Programming – 2015-2 42
3.1.2 Step 2: Compile with mashc
Programming language compilers usually have boring names formed by
adding “c” to the end of the name of the language; e.g. cc.
Compile a MaSH program to Java with a command like:
$ mashc Program.mash
For the program Hello.mash, the command will be:
$ mashc Hello.mash
If the program has no errors that the compiler (mashc) can find, it will
create an output file: Hello.java.
1001ICT Introduction To Programming – 2015-2 43
3.1.3 Step 3: Compile with javac
Compile a Java program with a command like:
$ javac Program.java
For the program Hello.java, the command will be:
$ javac Hello.java
If the program has no errors that the compiler (javac) can find, it will
create an output file: Hello.class.
javac is a translator from the Java language to Java Java bytecode.
Java bytecode is the machine code for the Java virtual machine (JVM).
1001ICT Introduction To Programming – 2015-2 44
3.1.4 Step 4: Run with java
Run a Java program with a command like:
$ java Program
For the program Hello, the command will be:
$ java Hello
java is the Java virtual machine for your computer.
It interprets the Java bytecode, which means it executes it.
Compilers translate. Interpreters execute.
1001ICT Introduction To Programming – 2015-2 45
3.1.5 All steps (Windows): mash
The file mash.bat is installed on the lab PCs.
It is a DOS batch file.
Batch files are scripts containing DOS commands to run in sequence.
To run all the steps (mashc, javac, java) in one command, type:
> mash Program
For the program Hello, the command will be:
> mash Hello
1001ICT Introduction To Programming – 2015-2 46
3.1.6 All steps (Mac and Linux): mc
The file mc is installed on the lab Macs.
It is a bash shell script, the Unix equivalent to a Windows batch file.
To run all the steps (mashc, javac, java) in one command, type:
] mc Program
For the program Hello, the command will be:
] mc Hello
1001ICT Introduction To Programming – 2015-2 47
3.1.7 The MaSH judge
For console programs only, there is an online service that can test whether
a program is the correct solution to one of a list of problems.
It can be used from any device with a web browser at:
http://www.ict.griffith.edu.au/arock/MaSH/mash.cgi?
problems
or from the command line with a mashj command like this:
$ mashj problem-id Program.mash
where problem-id is a string of characters that identifies the problem
being solved.
1001ICT Introduction To Programming – 2015-2 48
For example, let’s submit Hello.mash for judging.
$ mashj 0001-hello Hello.mash
Judging problem "0001-hello".
Success! Your program is correct.
Additional feedback:
Congratulations!
Runtime = 0.256942 seconds
$
In this case our submission is correct. Other outcomes could include, wrong
answer, or format error.
If you get a format error, check the capitalisation, punctuation and spelling
of your output.
1001ICT Introduction To Programming – 2015-2 49
3.1.8 MaSH Commands Summary
Here is a summary of the MaSH and java commands you will use most
often for console programs.
Compiling and running programs
I want to... on Windows on Mac OS X / Linux
compile and run a pro-
gram.
> mash Program ] mc Program
Sending programs to the judge
$ mashj problem-id Program.mash
There is a more complete version of this summary at the front of the A5
format lecture notes.
1001ICT Introduction To Programming – 2015-2 50
3.2 Understanding a console MaSH program
3.2.1 The import directive
import console;
println("Hello, World!");
The red bit is called an import directive.
It makes stuff happen at compile time.
It tells mashc to look for a file called console.mashenv.
The file console.mashenv contains instructions to mashc as to how to
translate a program intended to run in the console environment.
We will use a different environment nxt.mashenv for programming a
Lego Mindstorms robot.
1001ICT Introduction To Programming – 2015-2 51
Java also has an import directive.
Most Java programs require several.
The Hello program we started with could have had this at the top:
import java.lang.System;
It is not required, however, as that part of the Java programming environ-
ment is always imported by default.
MaSH is simpler.
Every MaSH program imports just one environment.
1001ICT Introduction To Programming – 2015-2 52
3.2.2 The statement
import console;
println("Hello, World!");
The blue bit is a statement.
It makes stuff happen at run time. It is a direct command to do something.
Like most statements (and import directives) it ends with a semicolon (;).
There are many kinds of statements in Java.
This kind is a procedure call.
println is the name of a method.
A method is a chunk of program code given a name.
This one is defined somewhere else (in the console environment).
1001ICT Introduction To Programming – 2015-2 53
The println method carries out an action, so it is the kind of method
called a procedure.
Always, after a method’s name come parentheses, ( and ).
Between the parentheses comes a value that is being passed to the method
to operate on.
Values passed to methods are called parameters or arguments.
This value is a string of characters to print. The double quotes delimit the
string.
Some questions that you should be asking:
• How do you learn all the rules about how to write statements?
• How do you find out what methods there are and what they do?
1001ICT Introduction To Programming – 2015-2 54
3.3 Section summary
This section covered:
• how to save a MaSH program in a text file with the right kind of name;
• how to use mashc to translate a MaSH program into a Java program;
• how to use javac to translate a Java program into a bytecode pro-
gram;
• how to use java to interpret the bytecode program;
• the mash shortcut to do them all in sequence;
• the MaSH import directive;
• a MaSH statement consisting of a procedure call.
1001ICT Introduction To Programming – 2015-2 55
3.4 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 56
3.5 Self-practice exercises
Do these in your own time.
1. Write any MaSH program that compiles, and submit it to the MaSH
Online judge, as practice using the judge. (MaSH Online: 0000-
compile. This is the problem-id for the online MaSH judge, and links
to the problem on the web site.)
2. Write a help program that prints a summary of the batch file or script
commands used to compile and run/upload MaSH programs.
3. Write a program that prints this example of ASCII art. (MaSH On-
line: 0002-Mona.)
1001ICT Introduction To Programming – 2015-2 57
o8%8888,
o88%8888888.
8’- -:8888b
8’ 8888
d8.-=. ,==-.:888b
>8 ‘˜‘ :‘˜’ d8888
88 ,88888
88b. ‘-˜ ’:88888
888b ˜==˜ .:88888
88888o--:’:::8888
‘88888| :::’ 8888b
8888ˆˆ’ 8888b
d888 ,%888b.
d88% %%%8--’-.
/88:.__ , _%-’ --- -
’’’::===..-’ = --.
1001ICT Introduction To Programming – 2015-2 58
4 Lego Mindstorms
4.1 Robotics?
Any programming course will set students programming problems.
The problems have to be about something or the programs don’t really do
anything.
We have selected robotics as a problem area, because:
• the problems are easy to describe and understand (e.g. Follow a line.);
• but the solutions are not always trivial;
• there is robotics research going on within our School; and
• it’s more fun than most.
1001ICT Introduction To Programming – 2015-2 59
4.2 Robotics theory
All you need to know about robotics is three words: sense; plan; act.
Sense – Robots need sensors to detect their location or objects to act upon.
Plan – Robots need to decide what to to. This is the programming part.
Act – Robots need actuators (motors) to move within their environment
and act upon objects.
1001ICT Introduction To Programming – 2015-2 60
4.3 Lego?
Lego Mindstorms are the commercial version of a project at the MIT Media
Laboratory, The Programmable Brick.
The problem with most mobile robotics research is the cost of designing,
making and maintaining the physical robotic hardware.
Lego Technics sets have a lot of interesting machine parts in a great variety
of standard sizes.
The addition of a computer and sensors is all that is required to make it
good for prototyping new robots cheaply.
A Sony AIBO (the discontinued dog) cost about $3000, and you only got
one kind of robot.
A Roboraptor/pet/sapien costs about $100-200, and does a lot less.
A Mindstorms kit costs about $500 and can make as many kinds of robots
as your creativity permits.
1001ICT Introduction To Programming – 2015-2 61
4.4 The RCX
The original Lego Mindstorms kits
were comprised of a selection of
Lego Technics components plus:
• the “programmable brick”,
called the Robotic Command
eXplorer (RCX);
• sensors; and
• motors.
Programs are downloaded from a
PC via a very slow infra-red inter-
face.
1001ICT Introduction To Programming – 2015-2 62
Programs are written for the RCX on a PC (Windows, Mac, Linux) and
downloaded via infra-red to the RCX.
Programming languages for the RCX include:
• Robolab Pilot – graphical, but limited;
• Robolab Inventor – graphical, fully featured;
• Lejos – Java;
• Brick OS – C; and
• Logo.
Previously, for this course, we used Robolab Inventor and Lejos Java.
1001ICT Introduction To Programming – 2015-2 63
4.5 The NXT
The RCX has been superceded by the
NXT (which does not seem to stand for
anything).
Robolab can be used with the NXT, though not as easily.
There is a Lejos Java programming system. Though it is still under devel-
opment, it is working well enough to use in this course.
The NXT is much more capable than the RCX, and programs download
much faster via a direct USB cable.
1001ICT Introduction To Programming – 2015-2 64
4.6 NXT hardware
The NXT can:
• receive information from sen-
sors via 4 input ports (1, 2, 3,
4);
• receive information from its
front panel buttons;
• make sounds;
• control motors (and/or lamps) via 3 output ports (A, B, C);
• receive information from motors;
1001ICT Introduction To Programming – 2015-2 65
• display graphics and text in its liquid crystal display (LCD); and
• communicate via Bluetooth.
The 4 input ports: 1; 2; 3;
and 4.
The USB port and the 3
output ports: A; B; and C.
1001ICT Introduction To Programming – 2015-2 66
The buttons: ENTER (orange); ESCAPE; LEFT;
and RIGHT.
Press ENTER to turn the NXT on.
The Lejos start-up screen.
If it starts any other way, then
the NXT needs to have the Lejos
firmware installed.
1001ICT Introduction To Programming – 2015-2 67
The Lejos main menu screen.
To find a program to run, select
Files.
Press ESCAPE to turn the NXT off.
The file list.
Program files have the extension
.nxj.
Select a file and press ENTER to
see the options for that file.
1001ICT Introduction To Programming – 2015-2 68
File options.
Choose Execute program to run it.
If you hear a buzz and see this
screen your program has crashed
because of a programming error.
Press ENTER and ESCAPE to-
gether to turn the NXT off.
1001ICT Introduction To Programming – 2015-2 69
If you hear a buzz and see a screen
like this, the nxt programming en-
vironment has detected a program-
ming error.
Press ESCAPE to terminate the
program.
You will have plenty of time to explore the other menu options in labs.
1001ICT Introduction To Programming – 2015-2 70
4.7 Actuators
4.7.1 Motors
Both RCX (left) and
NXT (right) motors
may be used with the
NXT.
They can be run forward or backwards at power levels 0 to 100.
4.7.2 Lamps
Tiny lamps may be powered at levels 0 to 100.
1001ICT Introduction To Programming – 2015-2 71
4.8 Sensors
4.8.1 Touch sensors
Both RCX (left) and NXT (right) touch
sensors may be used with the NXT.
They are simple switches.
4.8.2 Light sensors
Both RCX (left) and NXT (right) light sen-
sors may be used with the NXT.
Light sensors measure brightness, they are not cameras.
They have a floodlight built-in so that they can illuminate a surface to mea-
sure the brightness of reflected light. The NXT light sensor’s floodlight can
be turned off.
1001ICT Introduction To Programming – 2015-2 72
4.8.3 Sound sensors
The NXT sound sensor measures sound volume.
4.8.4 Ultrasonic proximity sensors
The NXT ultrasonic proximity sensor measures the
distance to a solid object.
1001ICT Introduction To Programming – 2015-2 73
4.8.5 Rotation sensors
Rotation (or angle) sensors
measure how much an axle
rotates.
An RCX rotation sensor (left) registers 16 counts per full 360 degree rota-
tion of the axle.
An NXT rotation sensor is built into every NXT motor. It registers 360
counts per full 360 degree rotation of the axle.
Both can count up or down, depending on the direction the axle is turning.
1001ICT Introduction To Programming – 2015-2 74
4.9 Programming NXT robots
To program a robot, you need to know:
• what sensors it has and which
ports they are plugged into;
• what actuators it has and which
ports they are plugged into; and
• which direction to turn motors on (forward or backward) to cause
desired actions.
This information will be posted on the course web site for each robot you
will program.
1001ICT Introduction To Programming – 2015-2 75
4.10 Section summary
This section covered:
• why we are learning programming using robotics problems;
• how robots sense, plan, and act;
• a brief description of the RCX;
• an introduction to the NXT, its inputs, outputs, and buttons;
• how to run a program using the Lejos firmware’s menus;
• the kinds of motors, lamps and sensors; and
• what you need to know about a robot to program it and where to find
it.
1001ICT Introduction To Programming – 2015-2 76
4.11 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 77
5 Hello, NXT!
In this section we learn how to compile MaSH (and Java) programs for the
NXT, and how to upload them.
1001ICT Introduction To Programming – 2015-2 78
5.1 Procedures come from environments
In our first MaSH program:
import console;
println("Hello, World!");
• We import the console environment, because the program will run
on a PC and we want to print stuff on the console screen.
• We use the println(String) procedure, because that is one of
the procedures in the console environment that will output a string
to a personal computer (PC)’s console.
• Procedures are not built into or predefined in the language.
• In a different environment, there will be different procedures.
1001ICT Introduction To Programming – 2015-2 79
5.2 A Hello program for the NXT
Let’s write a program that puts a hello message on the screen of an NXT.
Some considerations:
• We must import the right environment: nxt.
• A procedure in the nxt environment that puts text on the screen is
drawString(String, int, int).
Where int and int indicate we have to supply numbers, not just the
string.
The numbers are the column and row on the screen at which to start
drawing the string.
1001ICT Introduction To Programming – 2015-2 80
• When the program ends, the screen reverts to the Lejos menus, so we
need to get the program to pause until we have read the text.
We can make the program wait until a touch sensor is pressed, before
it ends.
There’s a procedure for that: waitForPush(int).
The number is the input port number that a touch sensor is plugged
into.
1001ICT Introduction To Programming – 2015-2 81
• If a program uses a sensor, that sensor has to be set up.
There’s a procedure for that: setUpSensor(int, int).
The first number is the input port number.
The second number is a number used to select the kind of sensor that
is plugged into that port.
To avoid having programs littered with numbers with special mean-
ings that you would not remember and would need to look up, the
nxt environment defines some symbolic constants: TOUCH, SOUND,
...
• If we choose input port 4, this program will work on a Tricorder.
1001ICT Introduction To Programming – 2015-2 82
Putting it all together:
import nxt;
setUpSensor(4, TOUCH);
drawString("Hello, NXT!", 0, 4);
waitForPush(4);
This is the program you compile and run in Lab 2.
1001ICT Introduction To Programming – 2015-2 83
5.3 Compiling and running a MaSH NXT program
5.3.1 Step 1: Create the program file
Use your favourite text editor to create a text containing the text of the
program.
The file must have a name that ends with the extension .mash.
The main part of file name must be a Java identifier, starting with an upper
case letter.
5.3.2 Step 2: Compile with mashc
Compile a MaSH program with a command like:
$ mashc Program.mash
1001ICT Introduction To Programming – 2015-2 84
5.3.3 Step 3: Compile with nxjc
Different! Compile the Java program with a command like:
$ nxjc Program.java
nxjc.bat is a batch file that makes javac use the Lejos NXJ libraries.
5.3.4 Step 4: Link with nxjlink
Linking means bundling up all the compiled code into one file.
Do this with a command like:
$ nxjlink Program -o Program.nxj
1001ICT Introduction To Programming – 2015-2 85
5.3.5 Step 5: Upload to the NXT with nxjupload
Do this with a command like:
$ nxjupload Program
5.3.6 Step 4 and 5 shortcut
The nxj command can be used to link and upload in one step.
$ nxj Program
1001ICT Introduction To Programming – 2015-2 86
5.4 Convenience batch files for Windows
This is getting to be a lot of steps!
We have installed batch files in the lab PCs.
5.4.1 For console programs
As mentioned before, command:
> mash Program
will compile a program with mashc then javac and then run it with
java. (Don’t type any filename extension!)
1001ICT Introduction To Programming – 2015-2 87
5.4.2 For NXT programs
The command:
> mashn Program
will compile a program with mashc and nxjc, then link and upload it with
nxj.
5.4.3 For RCX programs
The command:
> mashl Program
performs the equivalent for RCX programs.
1001ICT Introduction To Programming – 2015-2 88
5.5 Convenience shell script for Macs and Linux
For Unix (that is Mac OS X) and Linux, the previously mentioned bash
shell script works for all MaSH environments.
] mc Program
mc will compile a program with mashc then javac or nxjc and then run
it with java or link and upload it with nxj. (Don’t type any extension
other than .mash.)
1001ICT Introduction To Programming – 2015-2 89
5.6 Section summary
This section covered:
• an example program that uses the nxt environment;
• how to compile, link, and upload an nxt program; and
• the batch files for convenient compiling.
1001ICT Introduction To Programming – 2015-2 90
5.7 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 91
6 Syntax, Semantics and Compiler Phases
In this section we will discuss some topics that are common to all program-
ming languages and their compilers.
We learn a notation for describing the syntax of any programming language.
We learn some of the syntax of Java and MaSH using this notation.
1001ICT Introduction To Programming – 2015-2 92
6.1 Syntax versus semantics
When we learn a language, Java, C or French, we have to learn a lot of facts
and rules.
In general these can be sorted into two categories:
syntax: the grammar, how words and punctuation symbols must be ar-
ranged; and
semantics: what meaning words and symbols convey.
Fortunately programming languages are simpler than natural languages.
They have fewer words, simpler grammar and are unambiguous. Consider:
Time flies like an arrow.
Fruit flies like a banana.
1001ICT Introduction To Programming – 2015-2 93
6.2 Lexical syntax versus context-free grammar
We consider the syntax of languages at two levels:
lexical syntax: what are the punctuation symbols and how do you spell the
words; and
context-free grammar: how can you arrange the punctuation symbols and
the words – everything you can define about the language without
knowledge about how the meanings interrelate.
Find the lexical errors, grammatical errors and semantic errors in this:
There is three main political partys member’s with in the aus-
tralian senate: the Labor party; the Liberal partay, the Nation-
alparty; and the Greens..
1001ICT Introduction To Programming – 2015-2 94
6.3 Specifying and describing syntax
To describe the syntax of a language you can use natural language, or
special, formal languages designed just for the purpose of describing lan-
guages, or both.
The formal language we will use is the syntax diagram or railroad diagram.
If you can appreciate that a train on a train track can not make sharp turns,
then you can read these diagrams.
Start at the left. Any path you take that gets to the right end will produce a
syntactically correct text.
1001ICT Introduction To Programming – 2015-2 95
As you traverse the path, you meet text in boxes, the elements:
• Text that appears in a round-cornered (green-filled) rectangle appears
as-is (literally) in the program.
• Text that appears in a rectangle (orange-filled) represents a syntactic
element that is defined in another syntax diagram, the one with that
name at its top-left.
• Italicised text in a rectangle (yellow-filled) is an informal description.
The path can be red or black:
• A black path indicates that there can be whitespace between the ele-
ments.
• A red path indicates that there can be no whitespace between the ele-
ments. This is used exclusively for lexical syntax.
1001ICT Introduction To Programming – 2015-2 96
6.4 Elements of Java and MaSH syntax
6.4.1 Kinds of characters
Certain kinds of characters are appropriate in
different places in a Java program.
Separators are the punctuation symbols of the
language.
separator
(
)
{
}
[
]
;
,
1001ICT Introduction To Programming – 2015-2 97
A letter is an upper or lower case letter from the
modern Latin alphabet.
letter
a
...
z
A
...
Z
Ordinary digits are the decimal digits from 0 to
9.
digit
0
...
9
1001ICT Introduction To Programming – 2015-2 98
Whitespace characters are those characters that exist in a text file, but don’t
normally show up when the file is viewed. Common whitespace charac-
ters include the ordinary space, the tab character, the newline character that
marks the end of each line, and some much more rarely used others.
whitespace
space
tab
newline
...
In a program, the whitespace is really only significant if it separates two
tokens (e.g. identifiers) that could otherwise be taken as one token.
1001ICT Introduction To Programming – 2015-2 99
6.4.2 Java names
Programmers give names to things in programs: variables, methods, con-
stants, classes, ...
Names are called identifiers. The syntax of an identifier is:
Identifiers start with a letter, which
may then be followed by additional let-
ters, digits or underscores. Letters and
digits are defined below. No spaces are
permitted.
identifier
letter
digit
_
letter
Try to find the paths through the diagram for: x; Hello; 3M; and
Hello_2_You.
1001ICT Introduction To Programming – 2015-2 100
6.4.3 Comments
Comments are text for human readers only and are treated like whitespace
by compilers. Java has the same comment syntax as C++.
In C++, there are two kinds, of which one is the same as that used in the C
language.
comment
cComment
eolComment
1001ICT Introduction To Programming – 2015-2 101
A C-style comment may extend over many lines of text. It starts with the
characters /* and ends with */. There can be any amount of any characters
other than the sequence */ in between.
cComment
*/any characters
*/
not
/*
Example:
/* This is
all one comment. */
1001ICT Introduction To Programming – 2015-2 102
A C++-style end-of-line comment is for shorter comments, starts with //
and ends at the end of the line.
eolComment
newlineany characters
newline
not
//
Examples:
// This is one comment.
doSomething(); // This is another comment.
1001ICT Introduction To Programming – 2015-2 103
6.4.4 The grammar of MaSH programs at the statements level
A program begins with an import directive that selects the environment
within which this program will run.
Note that without selecting an environment, the program could not do any-
thing that the user could observe. It could not display anything or control
any hardware. The environments provide the methods by which these things
can be done.
After the import directive, comes the program in the no-method program
structure.
mashProgram
noMethodProgramimportDirective
1001ICT Introduction To Programming – 2015-2 104
An import directive starts with the keyword import, which is followed by
an identifier (the name of the environment), and ends with a semicolon.
Environment names should start with a lower case letter.
importDirective
;identifierimport
Example:
import console;
A no-method program consists of a sequence of statements.
noMethodProgram
statement
1001ICT Introduction To Programming – 2015-2 105
6.5 Compiler phases
A programming language compiler performs these operations in sequential
phases:
Lexical analysis: dividing the text up into tokens such as identifiers, num-
bers, strings...
Parsing: using the context-free grammar to recognise the structure of the
program.
Semantics checking: making sure that the semantic rules are being fol-
lowed.
Code generation: translating the program into the new language.
The compiler may detect errors in any of the first 3 phases and report them
and then not proceed any further.
1001ICT Introduction To Programming – 2015-2 106
6.6 Section summary
This section covered:
• the difference between syntax and semantics;
• the two levels of concern in syntax: lexical and context-free grammar;
• how to specify syntax with railroad diagrams, and how to read them;
• the definitions of some elements of Java and MaSH syntax using rail-
road diagrams; and
• the four main phases of a compiler: lexical analysis, parsing, seman-
tic checking, and code generation.
1001ICT Introduction To Programming – 2015-2 107
6.7 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 108
6.8 Self-practice exercises
Do these in your own time.
1. This program has an error in it. Fix it. (MaSH Online: 0002-error1.)
/*
** A program with an error in it.
/*
import console;
println("If you see this, you fixed it.");
1001ICT Introduction To Programming – 2015-2 109
7 Data types and Literal Values
We have started to use values in our programs.
What kinds of values appear in programs?
How do we express values in programs?
1001ICT Introduction To Programming – 2015-2 110
7.1 Types
Every value has a type that indicates what kind of information the value is.
For a while we need just three types:
int for whole numbers;
double for very big, very small or fractional numbers; and
String for text.
We have seen some of these names used to indicate the type of information
that must be supplied to procedures we have used.
1001ICT Introduction To Programming – 2015-2 111
In most programming languages, there are
two categories of types, simple and com-
pound.
Most Java compound types are objects.
type
simpleType
objectType
7.1.1 Simple types
The simple types contain one item of logical,
numeric or character data.
Values of these types need only a few bytes
of memory to store.
They can be moved or manipulated by a
computer’s central processor in just one ma-
chine code instruction.
simpleType
boolean
byte
char
double
float
int
long
1001ICT Introduction To Programming – 2015-2 112
7.1.2 Compound/Object types
To start with, we will consider only one object
type, the String.
objectType
String
In general, a compound type is an amalgam of multiple simple types.
A String is a sequence of characters.
One character may be stored in the simple type char.
A String may contain zero or more characters.
1001ICT Introduction To Programming – 2015-2 113
7.2 Literals
Literals represent a value explicitly. Every literal has a type.
literal
integerLiteral
floatingLiteral
booleanLiteral
characterLiteral
stringLiteral
1001ICT Introduction To Programming – 2015-2 114
7.2.1 Integer literals
Integer literals may be written in decimal, hexadecimal or octal. An l or L
at the end of the integer literal, means that the type on the integer is long.
By default, the type is int unless the value is too big to fit in an int.
integerLiteral
l
L
decimalNumeral
hexNumeral
octalNumeral
Octal digits are those we use when writing a
number in octal (base 8): 0 to 7.
octalDigit
0
...
7
1001ICT Introduction To Programming – 2015-2 115
Hexadecimal digits are those we use when writ-
ing a number in hexadecimal (base 16): 0 to 9
and the letters A to F in upper or lower case.
hexDigit
0
...
9
a
...
f
A
...
F
1001ICT Introduction To Programming – 2015-2 116
Unless the whole decimal numeral is just 0, a decimal numeral must not
start with a zero or it will be assumed to be an octal numeral. A non-zero
decimal numeral must start with a digit other than 0, and then more digits
may follow.
decimalNumeral
0
digit
digit
0
not
Examples: 0 = 010; 10 = 1010; 255 = 25510.
1001ICT Introduction To Programming – 2015-2 117
A hexadecimal numeral starts with 0x, which is followed by one or more
hexadecimal digits.
hexNumeral
hexDigit0x
Examples: 0x10 = 1610; 0xFF = 25510.
An octal numeral starts with 0, which is followed by one or more octal
digits.
octalNumeral
octalDigit0
Examples: 010 = 810; 0377 = 25510.
1001ICT Introduction To Programming – 2015-2 118
7.2.2 Floating point literals
A floating point literal is used to create values of type float or double,
for fractional, very large or very small numbers. It starts with a whole
number part, then a decimal point, then optionally the fractional digits, then
optionally an e or E that introduces an optionally signed exponent. An f or
F at the end of the floating point literal indicated that the type is float. A
d or D at the end indicates double. By default, the type is double.
floatingLiteral
f
F
d
D
digit
+
-
e
E
digit
.digit
Examples: 0.0; 0.01 = 1.0 × 10−2; 6.02e23 = 6.02 × 1023.
1001ICT Introduction To Programming – 2015-2 119
7.2.3 Boolean literals
Boolean values are represented by the keywords false and true.
booleanLiteral
false
true
1001ICT Introduction To Programming – 2015-2 120
7.2.4 Special character escape sequences
To put some special characters in character and string literals we use a spe-
cial sequence that starts with the special escape character \ (a backslash).
The next character indicates which character the whole escape sequence is
representing.
escapeSequence
n
t
’
"
\
\ escape sequence represents a ...
\n newline character
\t tab character
\’ single quote (apostrophe)
\" double quote character
\\ backslash character
1001ICT Introduction To Programming – 2015-2 121
7.2.5 Character literals
A character literal, of type char,
is usually just that character dis-
played between single quotes.
The single character can’t be a
backslash, single quote or the end
of a line. Instead of a single char-
acter, you can put one of the spe-
cial character escape sequences
between the quotes.
characterLiteral
’any character
’
\
newline
not
escapeSequence
’
Examples: ’A’; ’?’; ’\n’; ’\’’; ’\\’.
1001ICT Introduction To Programming – 2015-2 122
7.2.6 String literals
A string literal, of type
String, is usually just zero
or more characters displayed
between double quotes. The
characters can’t be back-
slashes, double quotes or the
ends of lines. Strings can
also contain the special char-
acter escape sequences.
stringLiteral
"
any character
"
\
newline
not
escapeSequence
"
Examples: "Hello, World!"; "Name:\t\"Mary\"\n".
1001ICT Introduction To Programming – 2015-2 123
7.3 Section summary
This section covered:
• Java’s simple types;
• the compound type String;
• How to express values, i.e. the lexical syntax of Java literals.
1001ICT Introduction To Programming – 2015-2 124
7.4 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 125
7.5 Self-practice exercises
Do these in your own time.
1. This program has errors in it. Fix them. (MaSH Online: 0002-error2.)
import console;
println(" ,-_|\");
println("/ \");
println("\_,-._/");
println(" v");
1001ICT Introduction To Programming – 2015-2 126
8 Console Procedures
The procedures we’re going to use are defined in the MaSH environments.
So far we have used the console environment’s println(String)
procedure.
What else is in there?
The full documentation (or application programming interface (API)) for
the console environment is on the course web site.
This is an extract that shows what procedures we can use now.
It is important to learn how to read the documentation that defines a proce-
dure and how to use it to write a call to that procedure.
It is not as simple as cut-and-paste.
1001ICT Introduction To Programming – 2015-2 127
8.1 Procedures
Basically the only procedures the console environment provides are those
for printing stuff.
Here is the definition of a procedure:
void print(String s)
Purpose: Writes string s to standard output.
Notes:
• The name of the method is print.
• The word void at the front indicates this is a procedure.
• What the procedure does is given in a paragraph tagged Purpose.
1001ICT Introduction To Programming – 2015-2 128
• The parentheses contain the types and names of the parameters we
have to supply values for when we call the method.
• This is an example call to this procedure, as it might appear in a pro-
gram you write.
print("This is a string.");
• We don’t write void.
• We don’t write the type of the parameter.
• We don’t write the name of the parameter.
• We do write an actual value that has the same type as the parameter.
• In the definition we call the type and name together, a formal param-
eter.
• In the call we write an actual parameter.
1001ICT Introduction To Programming – 2015-2 129
The rest of the procedures:
void print(long i)
Purpose: Writes integral i to standard output.
Notes:
• The parameter is declared as a long, but an int will be accepted.
• This is an example call to this procedure:
print(42);
1001ICT Introduction To Programming – 2015-2 130
void print(double x)
Purpose: Writes floating point number x to standard output.
void println()
Purpose: Writes a newline to standard output.
void println(String s)
Purpose: Writes string s and then a newline to standard output.
void println(long i)
Purpose: Writes integral i and then a newline to standard out-
put.
1001ICT Introduction To Programming – 2015-2 131
void println(double x)
Purpose: Writes floating point number x and then a newline to
standard output.
1001ICT Introduction To Programming – 2015-2 132
8.2 Section summary
This section covered:
• the definitions of all of the procedures in the console environment;
• the format of a definition;
• how to write a call to a procedure, given its definition; and
• the terms formal parameter and actual parameter.
1001ICT Introduction To Programming – 2015-2 133
8.3 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 134
9 NXT Procedures
This section is an extract from the documentation (API) of the nxt envi-
ronment.
It defines most of the nxt procedures.
These procedures will only work for some actual parameter values.
So the definitions usually come with preconditions.
Some values are specified with symbolic constants, so they are defined here
too.
1001ICT Introduction To Programming – 2015-2 135
9.1 Setting up sensors
At the start of a program, the sensor ports need to be set up to work with
the kind of sensor that is plugged into it. Sensors can be either the old RCX
kinds or the new NXT kinds.
The rotation sensor built into an NXT motor does not have to be set up.
1001ICT Introduction To Programming – 2015-2 136
9.1.1 Sensor kind constants
Constants are predefined names for some values.
The word final marks a constant.
The names for constants are always spelled in upper case.
final int TOUCH
Purpose: Constant to select sensor type touch (NXT or RCX).
final int LIGHT_FLOOD
Purpose: Constant to select sensor type light (NXT with the
floodlight on).
1001ICT Introduction To Programming – 2015-2 137
final int LIGHT_NOFLOOD
Purpose: Constant to select sensor type light (NXT with the
floodlight off).
final int LIGHT_RCX
Purpose: Constant to select sensor type light (RCX with the
floodlight on).
final int ROTATION_RCX
Purpose: Constant to select sensor type rotation (RCX).
1001ICT Introduction To Programming – 2015-2 138
final int SOUND
Purpose: Constant to select sensor type sound (NXT).
final int PROXIMITY
Purpose: Constant to select sensor type ultrasound proximity
(NXT).
1001ICT Introduction To Programming – 2015-2 139
9.1.2 Set-up procedure
void setUpSensor(int port, int type)
Purpose: Sets up the port to be a sensor of the given type.
Precondition: port is 1, 2, 3, or 4.
Precondition: type is TOUCH, LIGHT_FLOOD, LIGHT_NOFLOOD,
LIGHT_RCX, ROTATION_RCX, SOUND, or PROXIMITY.
1001ICT Introduction To Programming – 2015-2 140
9.1.3 Output port constants
final int A
Purpose: Constant to select port A.
final int B
Purpose: Constant to select port B.
final int C
Purpose: Constant to select port C.
1001ICT Introduction To Programming – 2015-2 141
9.2 Using touch sensors
These procedures provide waits for a touch sensor’s state to change.
They assume that the port number you provide as a parameter has been
set up as a touch sensor of either the RCX or NXT kind.
void waitForPush(int port)
Purpose: Makes the program wait until the touch sensor on
port is pushed.
Precondition: port is 1, 2, 3 or 4.
1001ICT Introduction To Programming – 2015-2 142
void waitForLetGo(int port)
Purpose: Makes the program wait until the touch sensor on
port is let go.
Precondition: port is 1, 2, 3, or 4.
1001ICT Introduction To Programming – 2015-2 143
9.3 Using light sensors
These procedures all assume that the port number you provide as a pa-
rameter has been set up as a light sensor, of either the RCX or NXT kind.
These procedures provide waits for the light level reported by a light sensor
to change.
void waitForLighter(int port, int dif)
Purpose: Makes the program wait until the light sensor reading
on port is increased by dif.
Precondition: port is 1, 2, 3 or 4.
Precondition: dif is between 0 and 100, inclusive. 0 is no
wait at all. Real light levels never really change by anything
like 100.
1001ICT Introduction To Programming – 2015-2 144
void waitForLight(int port, int light)
Purpose: Makes the program wait until the light sensor reading
on port is at least the desired light level.
Precondition: port is 1, 2, 3 or 4.
Precondition: light is between 0 and 100, inclusive.
void waitForDarker(int port, int dif)
Purpose: Makes the program wait until the light sensor reading
on port is decreased by dif.
Precondition: port is 1, 2, 3 or 4.
Precondition: dif is between 0 and 100, inclusive. 0 is no wait
at all.
1001ICT Introduction To Programming – 2015-2 145
void waitForDark(int port, int light)
Purpose: Makes the program wait until the light sensor reading
on port is at most the desired light level.
Precondition: port is 1, 2, 3 or 4.
Precondition: light is between 0 and 100, inclusive.
For NXT sensors, the floodlight may be turned on or off.
void setFloodlight(int port, boolean floodlight)
Purpose: Turn the floodlight of the light sensor on port on or
off.
Precondition: port is 1, 2, 3 or 4.
1001ICT Introduction To Programming – 2015-2 146
9.4 Using sound sensors
These procedures all assume that the port number you provide as a pa-
rameter has been set up as a sound sensor.
They provide waits for the sound level to change.
void waitForLouder(int port, int dif)
Purpose: Makes the program wait until the sound sensor read-
ing on port is increased by dif.
Precondition: port is 1, 2, 3 or 4.
Precondition: dif is between 0 and 100, inclusive. 0 is no wait
at all.
1001ICT Introduction To Programming – 2015-2 147
void waitForLoud(int port, int volume)
Purpose: Makes the program wait until the sound sensor read-
ing on port is at least the desired volume level.
Precondition: port is 1, 2, 3 or 4.
Precondition: volume is between 0 and 100, inclusive.
void waitForQuieter(int port, int dif)
Purpose: Makes the program wait until the sound sensor read-
ing on port has decreased by dif.
Precondition: port is 1, 2, 3 or 4.
Precondition: dif is between 0 and 100, inclusive.
1001ICT Introduction To Programming – 2015-2 148
void waitForQuiet(int port, int volume)
Purpose: Makes the program wait until the sound sensor read-
ing on port is at most the desired volume level.
Precondition: port is 1, 2, 3 or 4.
Precondition: volume is between 0 and 100, inclusive.
1001ICT Introduction To Programming – 2015-2 149
9.5 Using proximity sensors
These procedures all assume that the port number you provide as a pa-
rameter has been set up as an ultrasonic sensor.
They provide waits for the distance reported by an ultrasonic sensor to
change.
void waitForNearer(int port, int dif)
Purpose: Makes the program wait until the Ultrasonic sensor
on port senses that distance has decreased by dif cm.
Precondition: port is 1, 2, 3 or 4.
Precondition: dif is between 0 and 255, inclusive. 0 is no wait
at all.
1001ICT Introduction To Programming – 2015-2 150
void waitForNear(int port, int distance)
Purpose: Makes the program wait until the ultrasonic sensor
on port reports a distance which is at most distance cm.
Precondition: port is 1, 2, 3 or 4.
Precondition: distance is between 0 and 255, inclusive.
void waitForFurther(int port, int dif)
Purpose: Makes the program wait until the ultrasonic sensor
on port reports the distance has increased by dif cm.
Precondition: port is 1, 2, 3 or 4.
Precondition: dif is between 0 and 255, inclusive.
1001ICT Introduction To Programming – 2015-2 151
void waitForFar(int port, int distance)
Purpose: Makes the program wait until the ultrasonic sensor
on port reports a distance which is at least distance cm. A
distance of 255 means no object is in view.
Precondition: port is 1, 2, 3 or 4.
Precondition: distance is between 0 and 255, inclusive.
1001ICT Introduction To Programming – 2015-2 152
9.6 Using rotation sensors
An NXT rotation sensor registers 360 counts per full 360 degree rotation.
NXT rotation sensors are built into NXT motors and must be plugged into
port A, B or C. There is no need to call setUpSensor(int,int) to set
up these sensors.
An RCX rotation sensor registers 16 counts per full 360 degree rotation. It
must be plugged into port 1, 2, 3 or 4 and set up like other sensor kinds.
void waitForRotation(int port, int rotation)
Purpose: Makes the program wait until the counter in the rota-
tion sensor on port has changed by at least the absolute value
of rotation.
Precondition: port is 1, 2, 3, 4, A, B, or C.
1001ICT Introduction To Programming – 2015-2 153
9.7 Using motors
The following procedures apply to both NXT and RCX motors.
void motorForward(int port, int power)
Purpose: Make the motor on port go forwards at the given
power.
Precondition: port is A, B, or C.
Precondition: power is between 0 and 100, inclusive.
1001ICT Introduction To Programming – 2015-2 154
void motorBackward(int port, int power)
Purpose: Make the motor on port go backwards at the given
power.
Precondition: port is A, B, or C.
Precondition: power is between 0 and 100, inclusive.
void motorStop(int port)
Purpose: Stop the motor on port. Stopping a motor cuts the
power to it and stops it rotating.
Precondition: port is A, B, or C.
1001ICT Introduction To Programming – 2015-2 155
void motorFloat(int port)
Purpose: Float the motor on port. Floating a motor, cuts
power to it and lets it rotate freely.
Precondition: port is A, B, or C.
1001ICT Introduction To Programming – 2015-2 156
9.8 Using lamps
void lampOn(int port, int power)
Purpose: Make the lamp on port go on at the given power.
Precondition: port is A, B, or C.
Precondition: power is between 0 and 100, inclusive.
void lampOff(int port)
Purpose: Turns the lamp on port off.
Precondition: port is A, B, or C.
1001ICT Introduction To Programming – 2015-2 157
9.9 Making sounds
void beep()
Purpose: Beep once.
void twoBeeps()
Purpose: Beep twice.
void fallingBeeps()
Purpose: A few short beeps with descending tones.
1001ICT Introduction To Programming – 2015-2 158
void risingBeeps()
Purpose: A few short beeps with ascending tones.
void buzz()
Purpose: Makes a low buzz.
void pause(int t)
Purpose: Make no sound for t milliseconds.
void playTone(int frequency, int duration)
Purpose: Plays a tone, given its frequency (Hertz) and duration
(milliseconds).
1001ICT Introduction To Programming – 2015-2 159
9.10 Using the LCD
The LCD display can be used to display text and graphics.
9.10.1 Constants
final int LCD_WIDTH
Purpose: The width of the LCD display in pixels, equals 100.
final int LCD_HEIGHT
Purpose: The height of the LCD display in pixels, equals 64.
1001ICT Introduction To Programming – 2015-2 160
final int LCD_COLUMNS
Purpose: The width of the LCD display in character spaces,
equals 16.
final int LCD_LINES
Purpose: The height of the LCD display in character spaces,
equals 8.
9.10.2 Procedures
void clear()
Purpose: Clears the LCD display to all white.
1001ICT Introduction To Programming – 2015-2 161
void drawString(String s, int x, int y)
Purpose: Displays a string s on the LCD starting at column x
and line y.
Precondition: 0 ≤ x < LCD_COLUMNS.
Precondition: 0 ≤ y < LCD_LINES.
1001ICT Introduction To Programming – 2015-2 162
void drawInt(int i, int width, int x, int y)
Purpose: Displays integer 1 on the LCD starting at column x
and line y right justified within at least width spaces.
Precondition: 1 ≤ width ≤ 11.
Precondition: 0 ≤ x < LCD_COLUMNS.
Precondition: 0 ≤ y < LCD_LINES.
void scroll()
Purpose: Scrolls the screen up one text line.
1001ICT Introduction To Programming – 2015-2 163
9.11 Waiting for fixed times
void sleep(int ms)
Purpose: Makes the program wait for a requested number of
ms (milliseconds).
9.12 Terminating a program
void exit()
Purpose: Terminates the program.
1001ICT Introduction To Programming – 2015-2 164
9.13 Section summary
This section covered:
• most of the constants and procedures in the nxt environment; and
• the use of preconditions to specify requirements of actual parameters.
1001ICT Introduction To Programming – 2015-2 165
9.14 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 166
10 Numbers
In this section we will discuss some of what programmers need to know
about numbers.
Most programs have to use numbers somewhere.
Computer graphics is an inherently mathematical application.
The notations used in this section are mathematical, rather than those used
in programming languages.
1001ICT Introduction To Programming – 2015-2 167
10.1 Kinds of numbers
10.1.1 Natural numbers
The earliest kinds of numbers people used were the kinds of numbers you
need to count things, the counting numbers.
1,2,3, ...
Counting numbers have been with us a long time, longer than we have been
classifiable as Homo Sapiens, since there are animals that can count (up to
a few anyway), such as primates and birds.
At first, we had no concept of zero.
The counting numbers are also known as cardinal and natural numbers.
1001ICT Introduction To Programming – 2015-2 168
Most mathematicians and computing scientists would also include zero in
the natural numbers.
0,1,2,3, ...
There is an infinite number of them.
1001ICT Introduction To Programming – 2015-2 169
10.1.2 Integers
All of the positive and negative whole numbers and zero are together known
as the integers.
...,−3,−2,−1,0,1,2,3, ...
10.1.3 Rationals
The rational numbers are all the numbers you can represent as the ratio (or
fraction) of two whole numbers; e.g.
−1 = −1
1
, 0 = 0
1
, 0.5 = 1
2
, 3.333... = 10
3
1001ICT Introduction To Programming – 2015-2 170
10.1.4 Irrationals
There are numbers that can’t be represented as the ratio of two whole num-
bers; e.g.
√
2, e, pi
10.1.5 Reals
The real numbers are all of the rationals and irrationals.
1001ICT Introduction To Programming – 2015-2 171
10.1.6 Continuous versus discrete
To pick the kind of numbers needed to represent or solve a problem, the
most important choice is between:
continuous values – things that might have fractional values or are smoothly
varying – things that can be measured: weight, length, speed.
Use reals.
discrete values – things that can only have whole number values – count-
ing things.
Use naturals or integers.
1001ICT Introduction To Programming – 2015-2 172
10.2 Arithmetic operations
10.2.1 Addition
3 + 4 = 7
10.2.2 Subtraction
4 − 3 = 4 + (−3) = 1
3 − 4 = 3 + (−4) = −1
1001ICT Introduction To Programming – 2015-2 173
10.2.3 Multiplication
4 × 3 = 4 + 4 + 4 = 3 + 3 + 3 + 3 = 12
4 × (−3) = (−3) + (−3) + (−3) + (−3) = −12
10.2.4 Division
12 ÷ 4 = 3
12 ÷ 5 = 2or 2.4?
1001ICT Introduction To Programming – 2015-2 174
The answer to the second example can be 2, if we are only considering
whole numbers.
Sometimes we use a / instead of ÷.
12/5 = 2
Sometimes we are even more precise about indicating that we are doing
integer division. The word div always means integer division.
13div 5 = 2
1001ICT Introduction To Programming – 2015-2 175
10.2.5 Modulo
We all know that there is a bit left over in an integer division like the one
above.
At school we might have said:
13div 5 = 2 remainder 3
We can compute the remainder with the modulo operation, mod.
13 mod 5 = 3
1001ICT Introduction To Programming – 2015-2 176
10.2.6 Powers
32 = 3 × 3 = 9
33 = 3 × 3 × 3 = 27
31 = 3
30 = 1
1001ICT Introduction To Programming – 2015-2 177
10.2.7 Precedence
A mathematical expression with multiple mathematical operations in it,
might have several interpretations.
3 + 4 × 5 = 35or 23?
We resolve this with an order of precedence, that is what should we do first?
precedence operations example
highest unary + and − 2 × −3 = 2 × (−3) = −6×,div,÷, /,mod 3 + 4 × 5 = 3 + (4 × 5) = 23
lowest binary + and −
We can override this conventional order of precedence using parentheses.
(3 + 4) × 5 = 35
1001ICT Introduction To Programming – 2015-2 178
10.3 Bases
10.3.1 Decimal
We usually count in decimal, that is in base 10.
Not every culture in history has done this. In ancient Babylon they counted
in base 60. To this day there are 60 minutes to the hour, and 60 seconds to
the minute.
Decimal (and Babylonian, but not Roman) numbers are positional, that is
we have only a few symbols for numbers and the value of the symbol de-
pends on its position in the number.
123 = 1 × 102 + 2 × 101 + 3 × 100 = 100 + 20 + 3
Decimal numbers are written using the 10 digits 0,1,2, ...,9.
1001ICT Introduction To Programming – 2015-2 179
10.3.2 Binary
Binary numbers, that is numbers in base 2, are written using digits 0 and 1.
They are used in computing a lot, because they are easy to represent in an
electronic circuit. A switch that is on can represent 1, and one that is off
can represent 0.
Binary numbers are positional, like decimal numbers.
1010 = 1 × 23 + 0 × 22 + 1 × 21 + 0 × 20 = 8 + 0 + 2 + 0 = 10
10.3.3 Other bases
In computing we sometimes use bases 8 (digits 0, 1, ..., 7) and 16 (digits 0,
1, ..., 9, A, B, ..., F), because numbers in these bases are shorter than binary
numbers and very easy to convert to and from binary numbers.
1001ICT Introduction To Programming – 2015-2 180
10.4 Whole numbers in computers
Whole numbers are stored in computers in binary format.
They are saved by setting some number of switches to on and off.
There can only be a finite number of these switches per number, as there is
only a finite number of switches in any given computer’s memory.
That means a computer can not store natural numbers or integers (there are
infinitely many of them) – only subsets of them.
How big that subset is, depends on how much memory you want to use.
1001ICT Introduction To Programming – 2015-2 181
10.4.1 Bits, bytes, words
The word bit is derived from binary digit.
A bit is one binary digit, that is a 0 or a 1.
A bit can save a useful amount of information: yes or no; true or false.
A few bits in a row can save a number. For example, with three bits we can
count as follows: 000, 001, 010, 011, 100, 101, 110, 111.
That is we can count from 0 to 7 with three bits.
That is there are 8 different numbers you can express with 3 bits. It is no
coincidence that 8 = 23.
We usually choose a number of bits per binary number that is itself a power
of 2.
A byte is 8 bits.
With a byte, you can represent the numbers 0 to 255. 255 = 28 − 1.
1001ICT Introduction To Programming – 2015-2 182
To count different things we need different numbers of bits. For most count-
ing jobs as few as 16 bits are needed.
As time has progressed, computer hardware has been able to do arithmetic
operations with bigger and bigger binary numbers in one step.
For example an Apple 2 could only perform operations on bytes, but a
Power Mac G5 can perform operations on 64 bits at a time.
A word is a term used to describe a binary number of some number of bits,
usually the maximum that a given computer can handle in one step.
1001ICT Introduction To Programming – 2015-2 183
10.4.2 Negative numbers
To store a negative number in the binary memory of a computer we have to
use a bit to indicate that a number is positive or negative.
Usually this is the left-most bit.
For example, in a 16-bit word:
1001001001001001 must be a negative number; and
0111111111111111 is the biggest positive number you can store.
There are a couple choices as to how exactly negative numbers are repre-
sented.
The commonest is two’s complement.
1001ICT Introduction To Programming – 2015-2 184
10.5 Fractional numbers in computers
In a computer, to represent a fractional number, we store the best approx-
imation to a real number that we can with a floating point representation
using a finite number of bits.
Single precision uses 32 bits. Double precision uses 64 bits.
The bits are grouped into 4 parts:
• a sign bit;
• the mantissa;
• the exponent; and
• the sign of the exponent.
The number is represented like scientific notation: ±mantissa ×10±exponent .
1001ICT Introduction To Programming – 2015-2 185
The exponent lets us represent very small or very large numbers.
There are some special patterns of bits reserved for some special values:
• infinity; and
• Not a Number (NaN), the result you can get if a computation can’t
return a sensible result.
Single precision can only approximate numbers to about seven decimal
digit’s worth of precision. This is not accurate enough to calculate the aver-
age person’s income to the cent.
Unless the computer has very little memory or you need to store a very large
number of numbers, double precision should be used.
1001ICT Introduction To Programming – 2015-2 186
10.6 Section summary
This section covered:
• the kinds of whole numbers (naturals, integers, rationals, irrationals,
reals);
• arithmetic operations (especially modulo);
• precedence of operators;
• representing numbers in different bases;
• how whole numbers are represented in computers (bits, bytes, words);
• how fractional numbers are represented in computers.
1001ICT Introduction To Programming – 2015-2 187
10.7 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 188
11 Making Stuff Happen With Numbers
This section has these main aims:
• to introduce numeric types in Java;
• to introduce numeric variables in Java;
• to introduce declaration and assignment statements and expressions;
• to show how to call functions; and
• to show how to input and output numbers from a Java program.
1001ICT Introduction To Programming – 2015-2 189
11.1 Java’s main numeric types
11.1.1 int
We can store a subset of the integers in a binary word. How big that subset
is, depends on how big the binary word is.
Type int uses 32 bits.
With 32 bits we can work with integer values between −2147483648 (−231)
and 2147483647 (231 − 1).
11.1.2 long
Another type for whole numbers is long, which uses 64 bits, for values
between: −9223372036854775808 (−263) and 9223372036854775807 (263−
1).
1001ICT Introduction To Programming – 2015-2 190
11.1.3 float
Type float is for single precision (32 bit) floating point (fractional) num-
bers.
Never use it, unless saving memory is an issue.
11.1.4 double
Type double is for double precision (64 bit) fractional numbers.
1001ICT Introduction To Programming – 2015-2 191
11.2 Numeric literals (revision)
We have defined the syntax of numeric literals, back in section 7.
What are the types and decimal values of these literals?
3 3L 3000000000
3.0 3.0F 3.0D
3.0e9 3.0e-2
03 030 0x30
1001ICT Introduction To Programming – 2015-2 192
11.3 Variables
We store values in variables.
A variable is a container, like a box, that saves a value.
We give each variable a name.
For example we might create an int variable called i.
It is really an allocation of 32 bits of RAM, but we might visualise it like
this picture:
  3i
This variable currently contains the value 3.
There is always some value in a variable. There is no such thing as an empty
variable, because the physical bits of RAM don’t go away.
1001ICT Introduction To Programming – 2015-2 193
11.3.1 Variable names
A Java variable must have a name that begins with a lower case letter, after
which may come more letters of either case, digits, or underscores (_).
11.3.2 Keywords
Some words, made up only of letters and therefore meeting the description
of identifiers given above, are special keywords in the Java language (and
some of them are in MaSH too) and therefore can not be used as names for
variables, constants and methods.
The full list of these reserved words or keywords is given in the following
table.
1001ICT Introduction To Programming – 2015-2 194
abstract else interface switch
assert enum long synchronized
boolean extends native this
break false new throw
byte final null throws
case finally package transient
catch float private true
char for protected try
class goto public void
const if return volatile
continue implements short while
default import static
do instanceof strictfp
double int super
1001ICT Introduction To Programming – 2015-2 195
11.4 Simple statements
At this stage the only kinds of program statements we will consider are the
simple, unstructured kinds.
statement
simpleStatement
There are three categories of simple statements.
simpleStatement
emptyStatement
declarationStatement
expressionStatement
1001ICT Introduction To Programming – 2015-2 196
The empty statement is just a semicolon and does nothing.
emptyStatement
;
Declaration statements declare either variables or constants.
declarationStatement
;variableDeclaration
constantDeclaration
Expression statements are expressions followed by semicolons. The ex-
pressions are assignments (defined below) or procedure calls (what we have
been doing up until now).
expressionStatement
;assignment
methodInvocation
1001ICT Introduction To Programming – 2015-2 197
11.5 Declaring variables
A variable must be declared.
You do this by writing its type before the first time its name is used.
This is done in a new kind of statement.
A variable declaration begins with a type and then introduces at least one
new variable. Multiple new variables are separated by commas.
variableDeclaration
newVariable,
newVariabletype
Don’t forget to terminate the statement with a semicolon.
1001ICT Introduction To Programming – 2015-2 198
New variable introductions consist of the name of the new variable followed
optionally by the assignment operator and an expression representing the
initial value for this new variable.
newVariable
orExpression=
identifier
Examples:
double x;
double y = 0.0;
int i, j, k;
int m = 0, n = 0;
Note that = is a command for putting a value in a variable, and not for
asking if they were equal.
1001ICT Introduction To Programming – 2015-2 199
11.6 Initialising variables
Initialisation is just a fancy way of saying we are giving a variable its first
value.
Very often the right thing to initialise a variable with is zero, but not always.
It depends on the problem.
11.7 Incrementing variables
Incrementing is just a fancy way of saying we are adding a little more (usu-
ally one) to the value in a variable.
1001ICT Introduction To Programming – 2015-2 200
11.8 Assignment statements
An assignment uses the assignment operator (=) to put new values in pre-
viously declared variables.
Only variable names are permitted on the left hand side of an assignment
operator.
assignment
assignment
orExpression
=leftHandSide
leftHandSide
identifier
Don’t forget to terminate the statement with a semicolon.
Note the recursion in the diagram, that allows multiple assignments.
1001ICT Introduction To Programming – 2015-2 201
The variable can only hold one value at a time, and if we put
a new value into the variable, it must completely replace the
old value.
The new values are specified with expressions.
Expressions can contain literals and variable names, and
their values can be combined with operators.
Operators are symbols made up of one or more special char-
acters and represent actions like addition (+) and assign-
ment (=).
Simple assignment examples:
i = 3;
i = 3 + 1;
i = i + 1; // Increment i
operator
+
-
*
/
%
==
<=
>=
>
<
!=
!
&&
||
=1001ICT Introduction To Programming – 2015-2 202
Some important points about assignments:
• They are not equations as we known them from Mathematics.
• A variable name appearing on the right hand side of = is:
– indicating a source of value; and
– will not change what is in that variable.
• A variable name appearing on the left hand side of = is:
– indicating the destination for the computed value on the RHS;
and
– will change what is in that variable.
• The value on the RHS is fully computed before it is assigned to the
variable on the LHS.
1001ICT Introduction To Programming – 2015-2 203
11.9 Arithmetic expressions
An expression is a sequence of symbols that represent a value.
Java expressions use many of the same operations for arithmetic expressions
as are used in mathematics.
Often the limited set of characters available for writing programs means that
a different symbol must be used.
math Java math Java
literals 1.0,0 1.0, 0L negation − (unary) - (unary)
addition + + subtraction − (binary) - (binary)
multiplication × * division ÷,div, / /
modulo mod % parentheses ( ) ( )
Example unary minus: -3
Example binary minus: 7 - 2
1001ICT Introduction To Programming – 2015-2 204
11.9.1 Arithmetic operator precedence
The precedence of these operators is as normal for mathematics.
precedence operators
highest + (unary), - (unary)
*, /, %
lowest + (binary), - (binary)
Parentheses may be used to force the order in which the operations are
carried out.
1001ICT Introduction To Programming – 2015-2 205
11.10 Example program 1
This program declares an int variable and increments it, printing it at each
stage.
// Example1.mash
import console;
int i = 0;
println(i);
i = i + 1;
println(i);
1001ICT Introduction To Programming – 2015-2 206
Now the state of i is drawn before and after each statement.
undefinedi We don’t know what is in i.
int i = 0; Initialising i with 0.
  0i Now we know what’s in i.
println(i); Pass the value in i to println.
  0i i’s value is unchanged.
i = i + 1; Assign what was in i plus 1 to i.
  1i i has a new value.
println(i);
  1i
1001ICT Introduction To Programming – 2015-2 207
We can confirm this picture by inspecting the output:
$ mashc Example1.mash
$ javac Example1.java
$ java Example1
0
1
$
Putting extra printing statements in a program is a good way to find out
what is happening inside a program.
1001ICT Introduction To Programming – 2015-2 208
11.11 The MaSH debugger
Being able to see what values are in the variables in a program is a very
good way to understand it.
For console MaSH programs, we can do that with the MaSH debugger
window.
To invoke this window compile with mashc like this:
$ mashc +debug Example1.mash
and compile with javac as normal, or:
• On Windows use the batch file mashd instead of mash.
• On Macs/Lunix use the script mcd instead of mc.
1001ICT Introduction To Programming – 2015-2 209
When the program is run, this window opens.
1001ICT Introduction To Programming – 2015-2 210
In the left pane of the window we can see
the source code of our program.
The blue triangle marker points to the
next statement that is about to be exe-
cuted.
Not even the first statement has been exe-
cuted yet.
1001ICT Introduction To Programming – 2015-2 211
In the right pane we have a table
showing the details of the vari-
ables in the program
In this table:
• warnings are red (undefined variables could be a problem);
• new things are green (everything so far is new);
• we see the name, type and value of our variable; and
• we see a column called “scope”.
We can ignore the scope column for now. It comes into play when we write
programs organised into methods.
1001ICT Introduction To Programming – 2015-2 212
The button executes just one statement, advancing the marker and
updating the table.
We can see that now the variable has been initialised to zero.
The program may be single stepped through or run slowly with the other
controls.
1001ICT Introduction To Programming – 2015-2 213
11.12 Declaring constants
We have used some predefined constants (like A and TOUCH) from the nxt
environment.
We can define new constants in MaSH programs using the keyword final.
Always give constants names that are in all upper case.
constantDeclaration
newConstant,
newConstanttypefinal
newConstant
orExpression=identifier
Don’t forget to terminate the statement with a semicolon.
You must assign a value, and that value can never be changed again.
1001ICT Introduction To Programming – 2015-2 214
Example constants:
final double GST_RATE = 10.0; // percent
final double C = 2.99792458e8; // m/s in a vacuum
final int MEANING_OF_LIFE = 42;
No need to define pi. It is predefined as PI.
It is a good idea to define constants that declare what sensors are pluggged
into what ports at the top of an NXT program.
For example a program for a Calibot-NXT might declare:
final int TOU = 1; // Touch sensor on port 1
final int LIG = 2; // Light sensor on port 2
final int MOT = A; // Motor on port A
1001ICT Introduction To Programming – 2015-2 215
11.13 Calling predefined functions
There are two basic kinds of methods:
procedures that perform an action; and
functions that return a value.
We have called procedures like println() to perform actions.
We call functions from expressions to use their result values.
1001ICT Introduction To Programming – 2015-2 216
11.13.1 Console functions
The console environment includes these functions for reading numbers
typed by the user.
int readInt()
Purpose: Returns the next integer from standard input.
Note that a type at the front (instead of void) indicates that this is a func-
tion that will return a value of that type.
long readLong()
Purpose: Returns the next long from standard input.
double readDouble()
Purpose: Returns the next double from standard input.
1001ICT Introduction To Programming – 2015-2 217
For example, to read a number into a program, use a variable declaration or
assignment with the function call on the RHS:
print("How tall are you (m)? ");
double height = readDouble();
Note that in an interactive program we print a prompt to ask the user for the
number, and if it matters, specify the units.
1001ICT Introduction To Programming – 2015-2 218
11.14 Robots with memories: NXT functions
We can use variables, constants, operators and expressions in the nxt en-
vironment, too.
Only the input functions change.
We use functions to obtain numeric values from sensors.
We can store the values in variables for later use, and calculate with them.
1001ICT Introduction To Programming – 2015-2 219
11.14.1 Using touch sensors
boolean isPushed(int port)
Purpose: Returns true if and only if the touch sensor on
port is currently pushed.
1001ICT Introduction To Programming – 2015-2 220
11.14.2 Using light sensors
int getLight(int port)
Purpose: Returns the current light sensor reading on port.
Precondition: port is 1, 2, 3 or 4.
For example, read the current light level from a light sensor in port 2.
final int LIG = 2; // Light sensor on port 2
setUpSensor(LIG, LIGHT_FLOOD);
sleep(500); // Allow the sensor to stabilise
int light = getLight(LIG);
1001ICT Introduction To Programming – 2015-2 221
11.14.3 Using sound sensors
int getVolume(int port)
Purpose: Returns the current volume sensor reading on port.
Precondition: port is 1, 2, 3 or 4.
11.14.4 Using proximity sensors
int getDistance(int port)
Purpose: Returns the current ultrasonic sensor reading on port
in centimetres. 255 means no object is in view.
Precondition: port is 1, 2, 3 or 4.
1001ICT Introduction To Programming – 2015-2 222
11.14.5 Using rotation sensors
int getRotation(int port)
Purpose: Returns the current rotation sensor reading from port.
Precondition: port is 1, 2, 3, 4, A, B, or C.
1001ICT Introduction To Programming – 2015-2 223
11.15 The mobile call billing problem
A mobile phone call usually is charged as follows:
• a fixed connection fee, say 20 c; and
• a charge per thirty seconds or part thereof, say 25c.
If I make a call of 67 seconds, what is the charge?
Everyone here could do this pretty quickly in our heads, but can we express
that thinking in a program (or mathematics)?
1001ICT Introduction To Programming – 2015-2 224
The hard part is working out how many lots of 30 s should be billed for.
At first glance this is easy. It is one more than the number 30 s.
67div 30 + 1 = 3
But this is not really a satisfying answer.
What if I had called for exactly 60 s?
60div 30 + 1 = 3
If the number of seconds divides evenly by 30, this kind of answer gets it
wrong.
It is nearly right – you basically divide the number of seconds by the 30,
and add something to account for the partially used 30 s.
1001ICT Introduction To Programming – 2015-2 225
Adding 1 after dividing is like adding 30 more seconds, that will always
give an extra charge, even when you don’t need one.
Why not add the extra before dividing – and why add a full 30?
Add 29 instead! This will not add an extra charge if you don’t need one.
(60 + 29)div 30 = 2
(67 + 29)div 30 = 3
1001ICT Introduction To Programming – 2015-2 226
11.15.1 Version 1
We can now make a MaSH program that calculates this (with an expression)
and prints them.
// Call1.mash
import console;
print("Call charge = ");
print(20 + (67 + 29) / 30 * 25);
println(" c");
1001ICT Introduction To Programming – 2015-2 227
11.16 print, println and string catenation
The print method always has one argument, the value to be printed.
println can have zero or one arguments and prints a newline after the
value (if there is one).
If the argument value is a string (e.g. "Hello, World!"), then that text
outputs to the console.
If the value has another type (e.g. int), it is first converted to a string, then
output to the console.
1001ICT Introduction To Programming – 2015-2 228
We can use a nice trick to save some statements.
+ does not always mean arithmetic addition.
It also concatenates two strings.
1001ICT Introduction To Programming – 2015-2 229
11.16.1 Version 2
A new, shorter version:
// Call2.mash
import console;
println("Call charge = " +
(20 + (67 + 29) / 30 * 25) + " c");
Note that the statement is too wide for the lecture slide. So it is spread over
two lines. Remember that we can add whitespace pretty much anywhere to
make a program more readable.
1001ICT Introduction To Programming – 2015-2 230
11.16.2 Version 3 – with a constant and an input
The above program solves the specific instance of the problem at hand. But
a useful program solves it in general, for any input number.
We will assume that the call connection fee and the other charges are changed
infrequently. So we will make them constants declared at the top of the pro-
gram.
Should they change, I can just change the definitions of the constants.
The durations of calls will change every time I use the program. Read that
value into a variable and rewrite the calculations so that they use the variable
and the constants.
1001ICT Introduction To Programming – 2015-2 231
// Call3.mash
import console;
final int CONNECT_FEE = 20; // cents
final int UNIT_FEE = 25; // cents / unit
final int UNIT = 30; // seconds
print("Call duration (s): ");
int duration = readInt();
println("Call charge = " +
(CONNECT_FEE +
(duration + UNIT - 1) / UNIT * UNIT_FEE)
+ " c");
1001ICT Introduction To Programming – 2015-2 232
11.17 Section summary
This section covered or revised:
• Java’s types for numbers;
• how to represent a number in a program with a numeric literal;
• how to declare variables and constants and assign values to them;
• how to write numeric expressions;
• what numeric input functions are provided by the MaSH environ-
ments;
• how to print numbers with string labels; and
• the MaSH debugger window.
1001ICT Introduction To Programming – 2015-2 233
11.18 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 234
11.19 Self-practice exercises
1. Write a program that reads two ints and prints their sum.
(MaSH Online: 0002-plus)
2. Write a program that calculates and prints the surface area of a cube,
given its edge length. The output number must be rounded to one
decimal place. Hint: use a format function from the console
environment to display the output to exactly one decimal place.
(MaSH Online: 0010-cube)
3. Write a program that converts degrees Fahrenheit to degrees Celsius.
Does it work for all temperatures? Try: inputs of 100, 70, 0, and −40.
The output numbers must be rounded to one decimal place.
(MaSH Online: 0011-F2C)
1001ICT Introduction To Programming – 2015-2 235
4. Write a program that converts fuel efficiencies in miles-per-gallon to
litres-per-100 kilometres. The online judge wants the output format-
ted like this:
50.0 M/g = 4.7 l/100km
(MaSH Online: 0012-fuel)
1001ICT Introduction To Programming – 2015-2 236
12 Booleans
A computer program typically needs to carry out different actions, depend-
ing on various circumstances, like different values in variables, or current
sensor inputs.
These decisions are usually of the yes/no or true/false kind.
For example:
Is the value in x greater than 0?
Is the touch sensor button in?
Often the decisions involve a combination of more than one of these simple
questions.
Is the value in x greater than 0 and is the touch sensor button in,
or is the value in x less than or equal to 0?
1001ICT Introduction To Programming – 2015-2 237
In this section we will introduce the kinds of symbols used in mathematics
and logic to:
• represent yes/no or true/false values;
• compare values and thereby create true/false values;
• combine true/false values.
This will help you to write programs that do more than follow simple se-
quences.
1001ICT Introduction To Programming – 2015-2 238
12.1 Boolean values
We call the logical values True and False Booleans after George Boole,
who invented Boolean algebra, that is reasoning and logic with symbols,
not with just words.
symbol means
F false/no
T true/yes
1001ICT Introduction To Programming – 2015-2 239
12.2 Relational operators
We use relational operators to compare values and thereby create Boolean
values.
The values we can compare include all types (for example numbers and
Booleans themselves), so long as we compare things of the same type (for
example, numbers with numbers, but not a number with a Boolean).
symbol means symbol means< less than > greater than≤ less than or equal to ≥ greater than or equal to= equal to ≠ not equal to
For example, x > 0 is an expression with a Boolean value.
1001ICT Introduction To Programming – 2015-2 240
More examples: If x contains 3 and y contains −3...
expression value
x < 10 T
y ≤ 10 T
x < y F
x + y = 0 T
x ≠ y T
x ≥ y T
x ≤ y F
1001ICT Introduction To Programming – 2015-2 241
12.3 Boolean operators
Boolean operators are symbols used in Boolean algebra to combine Boolean
values.
Typically we want to:
• negate a value (change T to F or F to T);
• see if both of two values are T;
• see if at least one of two values are T;
• see if only one of two values are T.
1001ICT Introduction To Programming – 2015-2 242
operator means examples¬ not ¬T, ¬p, ¬(x < 10)∧ and T ∧ F, p ∧ q, x < 10 ∧ y = 0∨ or T ∨ F, p ∨ q, x < 10 ∨ y = 0
xor exclusive or TxorF, pxor q, x < 10xor y = 0
These truth tables show precisely how these operators combine Boolean
values.
p ¬p
F T
T F
p q p ∧ q
F F F
F T F
T F F
T T T
1001ICT Introduction To Programming – 2015-2 243
p q p ∨ q
F F F
F T T
T F T
T T T
p q pxor q
F F F
F T T
T F T
T T F
Note that when we say “or” in English we most often mean xor, but what
we will use most often in programs is ∨.
pxor q is the same as (p ∧ ¬q) ∨ (¬p ∧ q).
1001ICT Introduction To Programming – 2015-2 244
12.3.1 Precedence
Relational and Boolean operators can be mixed with arithmetic operators in
expressions.
precedence operations
highest unary + and −, ¬×,div,÷, /,mod
binary + and −<, ≤, >, ≥, =, ≠∧
lowest ∨, xor
Examples: If x contains 3 and y contains −3...
expression value¬(x < 10) F
x > 10 ∧ y ≤ 10 F
x > 10 ∨ y ≤ 10 T
1001ICT Introduction To Programming – 2015-2 245
12.4 Section summary
This section covered:
• the Boolean values T and F;
• the relational operators that can create Boolean values;
• the Boolean operators (not, and, or, exclusive or); and
• the precedence of Boolean and relational operators relative to the
arithmetic operators.
1001ICT Introduction To Programming – 2015-2 246
12.5 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 247
13 Java Booleans
Java has a type for Boolean values, and operators for combining them.
We use Boolean values to decide when to loop or execute alternate actions.
13.1 The boolean type
The symbol boolean is the type in Java that includes only the values
false and true.
1001ICT Introduction To Programming – 2015-2 248
13.2 Java relational operators
These are operators that return boolean values:
Math Java
less than < <
less than or equal to ≤ <=
greater than > >
greater than or equal to ≥ >=
equal to = ==
not equal to ≠ !=
Note that Java’s = means assignment.
Use these operators to compare things with the same types.
1001ICT Introduction To Programming – 2015-2 249
13.3 Java Boolean operators
These are operators that combine boolean values:
Math Java
not ¬ !
and ∧ &&
or ∨ ||
&& and || are short circuit operators.
1001ICT Introduction To Programming – 2015-2 250
The truth table for ∧:
p q p ∧ q
F F F
F T F
T F F
T T T
indicates:
• T ∧ q = q; and
• F ∧ q = F (regardless of what q is).
So there is no point in evaluating q, if it comes after F∧.
&& will not evaluate its right-hand-side if its left-hand-side is false.
1001ICT Introduction To Programming – 2015-2 251
The truth table for ∨:
p q p ∨ q
F F F
F T T
T F T
T T T
indicates:
• F ∨ q = q; and
• T ∨ q = T (regardless of what q is).
So there is no point in evaluating q, if it comes after T∨.
|| will not evaluate its right-hand-side if its left-hand-side is true.
1001ICT Introduction To Programming – 2015-2 252
13.4 Summary of Java operator precedence
precedence operators
highest !, +, -
*, /, %
+, -
<, <=, >, >=
==, !=
&&
lowest ||
1001ICT Introduction To Programming – 2015-2 253
13.5 Uses of Booleans in programming
These are the most common uses for Booleans in programming:
13.5.1 Flags
The purpose of all variables is to save information created in one part of a
program for use in another part.
Boolean variables are no different.
When one part of a program wants to send a true/false signal to another
part, it can do so with a boolean variable, or flag.
1001ICT Introduction To Programming – 2015-2 254
13.5.2 Boolean parameters
Many methods have boolean parameters that cause the methods’ be-
haviour to change.
For example here is a method in the nxt environment for drawing on the
NXT’s LCD.
void setPixel(boolean p, int x, int y)
Purpose: Set the pixel at (x, y). If p is true, the pixel is set to
black, white otherwise.
Precondition: 0 ≤ x < LCD_WIDTH.
Precondition: 0 ≤ y < LCD_HEIGHT.
1001ICT Introduction To Programming – 2015-2 255
13.5.3 Controlling program flow
Boolean values are used to make decisions that effect what statements will
be executed.
Normally the program starts executing statements from top to bottom.
The special statements that cause a program to repeat or choose not to exe-
cute some statments are the subject of the next section.
1001ICT Introduction To Programming – 2015-2 256
13.6 Section summary
This section covered:
• Java’s boolean type;
• Java’s relational operators;
• Java’s Boolean operators;
• a summary of the precedence of Java operators; and
• uses for Booleans in programming.
1001ICT Introduction To Programming – 2015-2 257
13.7 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 258
13.8 Self-practice exercises
1. Write a program that reads two booleans, p and q and prints the in-
clusive or of p and q.
(MaSH Online: 0013-or)
2. Write a program that reads two booleans, p and q and prints the ex-
clusive or of p and q.
(MaSH Online: 0013-xor)
1001ICT Introduction To Programming – 2015-2 259
14 Making It Happen – Again
This section takes us to the next level – being able to control which state-
ments are executed, depending on the current circumstances.
Loops are the most powerful feature of programmable machines.
Loops enable machines to do the boring repetitive work that humans can’t
or don’t want to do.
1001ICT Introduction To Programming – 2015-2 260
14.1 Kinds of loop structures
There are three main kinds of loops used in Java.
Which you use is determined by what you know and when you know it.
14.1.1 Definite loops
If you have some task to do and you know before you start how many times
it needs to be done, use a definite loop.
A definite loop is so named, because at the time it starts, we know definitely
how many times it will repeat the task.
1001ICT Introduction To Programming – 2015-2 261
14.1.2 Indefinite loops
If you have a task that if done some number of times will achieve some out-
come, but you can’t be sure how many times that is, you need an indefinite
loop.
There are two kinds of indefinite loop:
Pre-tested If you can tell whether the overall outcome has been achieved
before doing the task even once, use a pre-tested indefiniteLoop.
“Pre-tested” means the decision whether or not to do the task comes
before the task.
Post-tested But if you have to perform the task at least once before you
can tell if the overall outcome is achieved, use a post-tested indefinite
loop.
“Post-tested” means the decision whether or not to do the task again
comes after the task.
1001ICT Introduction To Programming – 2015-2 262
14.2 Blocks, scope and indenting
14.2.1 Blocks
A block is a sequence of zero-or-more statements enclosed in a pair of
braces, { and }.
block
}
statement
{
A block is used:
• to make a sequence of statements appear syntactically as one; and
• to limit the scope of variables.
1001ICT Introduction To Programming – 2015-2 263
14.2.2 Scope
A variable is “in scope” if it can be accessed.
The rules:
• A variable declared inside a block is in scope (visible and usable)
within that block, but not in scope outside of that block.
• A variable declared outside a block is in scope within that block.
The scope of a variable is related to its lifetime:
• As a program enters a block, the variables declared in the block have
memory allocated for them and they come into existence.
• When the program exits the block, the memory is released for reuse
and those variables no longer exist.
1001ICT Introduction To Programming – 2015-2 264
This example causes a scope error.
/*
** file: Scope.mash
** purpose: Demonstrates a variable out-of-scope.
*/
import console;
int i = 1;
{
int j = 2;
}
println("i = " + i);
println("j = " + j);
1001ICT Introduction To Programming – 2015-2 265
$ mashc Scope.mash
mashc error: Error on line 13: Variable "j" has
not been declared.
}
println("i = " + i);
println("j = " + j);
ˆ
|
1001ICT Introduction To Programming – 2015-2 266
14.2.3 Indenting
We can and usually do have nested blocks (blocks inside blocks) even in
simple programs.
We use indenting to show which statements are inside which blocks.
Exactly how indenting is done is an issue of style that programmers argue
over. What we all agree is that:
• it is an essential skill for all programmers;
• an opening { should be the last thing on a line;
• a closing } should usually be the only thing on a line;
• everything on the lines in between should be indented by 3 or 4
spaces.
1001ICT Introduction To Programming – 2015-2 267
14.3 Structured statements for loops
Java’s structured statements include: blocks; while statements; for state-
ments; do-while statements; and if-else statements.
structuredStatement
block
whileStatement
forStatement
doWhileStatement
ifElseStatement
if-else statements are the subject of a later section.
1001ICT Introduction To Programming – 2015-2 268
14.3.1 while statements
A while statement is a loop that executes a statement repeatedly while a
Boolean expression is true.
This is Java’s pre-tested indefinite loop.
A while statement consists of the keyword while, a Boolean expres-
sion enclosed in parentheses (the loop guard or condition), followed by the
statement that will be repeated.
whileStatement
statement)orExpression(while
The statement is usually a block.
The while loop is the only kind of loop you really need.
All loop types can be created with just this statement.
1001ICT Introduction To Programming – 2015-2 269
while loops are usually written like this, with a boolean loop condition
and a sequence of statements forming the loop body .
while (condition) {
body
}
Examples:
1. While a touch sensor is pressed, blink a lamp.
// Blink1.mash
import nxt;
final int TOU = 1; // Touch sensor port
final int LAM = A; // Lamp port
1001ICT Introduction To Programming – 2015-2 270
setUpSensor(TOU, TOUCH);
while (isPushed(TOU)) {
lampOn(LAM, 100);
sleep(200);
lampOff(LAM);
sleep(200);
}
A problem with this program is that unless the touch sensor is already
pressed, the loop condition is false and the lamp never blinks at all.
Pre-tested loops execute zero-or-more times.
Version 2:
// Blink2.mash
import nxt;
1001ICT Introduction To Programming – 2015-2 271
final int TOU = 1; // Touch sensor port
final int LAM = A; // Lamp port
setUpSensor(TOU, TOUCH);
waitForPush(TOU); // Ensure button is pushed.
while (isPushed(TOU)) {
lampOn(LAM, 100);
sleep(200);
lampOff(LAM);
sleep(200);
}
It is very common for while loops to require some initialisation so
that the loop condition can be sensibly applied the first time.
1001ICT Introduction To Programming – 2015-2 272
2. Build a doorbell.
A doorbell is a robot that waits for a button to be pushed and then
rings. It does this until its batteries run out.
For this we need a loop that never ends.
Usually infinite loops are the result of a programming error, but this
time it’s useful.
// Doorbell.mash
import nxt;
final int TOU = 1; // Touch sensor port
1001ICT Introduction To Programming – 2015-2 273
setUpSensor(TOU, TOUCH);
while (true) {
waitForPush(TOU);
playNote(XYLOPHONE, 880, 400);
pause(200);
playNote(XYLOPHONE, 440, 600);
}
1001ICT Introduction To Programming – 2015-2 274
3. Print HELLO 10 times.
This should really be done with a definite (for) loop, but it can be
done with a while loop.
// Hello10_1.mash
import console;
int i = 0;
while (i < 10) {
println("Hello");
i = i + 1;
}
Demonstrate this program using the MaSH debugger window.
1001ICT Introduction To Programming – 2015-2 275
14.3.2 do-while statements
A do-while statement is a loop that executes a statement once and then
repeats it while a Boolean expression is true.
Therefore it makes post-tested indefinite loops.
A do-while statement consists of the keyword do, the statement (usually
a block); the keyword while; a boolean expression enclosed in paren-
theses (the loop guards or condition), followed by a semicolon.
doWhileStatement
;)orExpression(whilestatementdo
1001ICT Introduction To Programming – 2015-2 276
do-while loops are usually written like this:
do {
body
} while (condition);
Since a do-while loop must execute the body one-or-more times, and a
while loop can execute the body zero-or-more times, the while loop is
more generally safe and useful.
1001ICT Introduction To Programming – 2015-2 277
14.3.3 for statements
A for statement is a loop that should be used to repeat a statement a definite
number of times.
This is Java’s definite loop.
A for statement consists of the keyword for, then a complicated three-
part definition that controls how many times the loop will execute (a for
control, defined below) enclosed in parentheses, followed by the statement
to be repeated.
forStatement
statement)forControl(for
The statement is usually a block.
As well as being definite loops, for statements are also pre-tested.
1001ICT Introduction To Programming – 2015-2 278
The three parts that control a for loop are:
1. the declaration and initialisation or reassignment of a loop counter
variable;
2. condition (a Boolean expression); and
3. an assignment that counts off each execution of the loop body.
These three things are separated by semicolons.
forControl
assignment;orExpression;variableDeclaration
assignment
1001ICT Introduction To Programming – 2015-2 279
for loops are usually written like this, with the initialisation of a
new loop counting variable, a Boolean loop condition that tests the loop
variable, and an increment (an assignment) that moves the loop variable
on to its next value.
for (initialisation; condition; increment) {
body
}
The for statement is pre-tested and equivalent to a while statement or-
ganised like this:
initialisation;
while (condition) {
body
increment;
}
1001ICT Introduction To Programming – 2015-2 280
Examples:
1. Print HELLO 10 times.
// Hello10_2.mash
import console;
for (int i = 0; i < 10; i = i + 1) {
println("Hello");
}
2. Print the numbers from 1 to 10 in increasing order.
// OneToTen.mash
import console;
1001ICT Introduction To Programming – 2015-2 281
for (int i = 1; i <= 10; i = i + 1) {
println(i);
}
3. Print the numbers from 1 to 10 in decreasing order.
// TenToOne.mash
import console;
for (int i = 10; i >= 1; i = i - 1) {
println(i);
}
Demonstrate these programs with the MaSH debugger.
1001ICT Introduction To Programming – 2015-2 282
14.4 Java loop statements summary
Use this table to easily pick the Java loop statement for a particular problem.
definite indefinite
pre-tested for while
post-tested do-while
1001ICT Introduction To Programming – 2015-2 283
14.5 Braces styles
There are two common styles of brace placement used with blocks in while
loops (and other structured statements). Use either, but be consisent.
• Style 1, matching braces in the same column as keyword:
while (condition)
{
body
}
• Style 2, opening brace on same line as keyword, closing brace in same
column as keyword:
while (condition) {
body
}
1001ICT Introduction To Programming – 2015-2 284
14.6 Section summary
This section covered:
• the difference between definite/indefinite pre/post-tested loops;
• blocks, scope and indenting;
• the syntax of Java’s looping control statements;
• tips on good coding practice and style.
1001ICT Introduction To Programming – 2015-2 285
14.7 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 286
14.8 Self-practice exercises
1. Write a program that prints the sum of all the numbers from 1 to 100.
You can make this a loop practice exercise, but if you are really clever,
don’t use a loop.
(MaSH Online: 0027-sum100)
2. Write a program that reads whole number n and then prints the sum of
all the whole numbers from 1 to n You can make this a loop practice
exercise, but if you are really clever, don’t use a loop.
(MaSH Online: 0028-sum1-n)
3. Write a program to print the first 100 triangular numbers. The trian-
gular numbers are 1,3,6,10,15, ...
1001ICT Introduction To Programming – 2015-2 287
4. (Advanced) Extend the average marks programs to also report the
standard deviation. Hint: There is a version of the formula that does
not require the mean to be calculated first.
1001ICT Introduction To Programming – 2015-2 288
15 Making It Happen – Or Not
This section completes the MaSH control level – being able to control which
statements are executed, depending on the current circumstances.
Selections allow programs to decide how to handle different situations.
Most programs combine loops and selections.
1001ICT Introduction To Programming – 2015-2 289
15.1 if-else statements
An if-else statement executes a statement if a condition is true. If the
condition is not true, then the statement in an optional else part is exe-
cuted.
The if-else statement starts with the keyword if, followed by the con-
dition in parentheses, followed by the statement (usually a block) to execute
if the condition is true. These may optionally be followed by the keyword
else and an alternate statement to execute if the condition is false.
ifElseStatement
statementelse
statement)orExpression(if
1001ICT Introduction To Programming – 2015-2 290
if-else statements are usually written like this, using a Boolean
condition to select between two alternate actions.
if (condition) {
action1
} else {
action2
}
Sometimes the choice is between performing some action or doing nothing.
if (condition) {
action
} else {
}
1001ICT Introduction To Programming – 2015-2 291
If there is a choice between three different actions two if-else statements
may be combined like this:
if (condition1) {
action1
} else if (condition2) {
action2
} else {
action3
}
If condition1 is true, then only action1 is performed.
If condition1 is not true and condition2 is true, then only action2
is performed.
If neither condition1 nor condition2 is true, then only action3 is
performed.
1001ICT Introduction To Programming – 2015-2 292
This can be extended to as many conditions and alternate actions as
needed.
if (condition1) {
action1
} else if (condition2) {
action2
} else if (condition3) {
action3
.
.
.
} else {
actionN
}
1001ICT Introduction To Programming – 2015-2 293
Examples:
1. Write a program that flatters the user on the basis of their age (two
cases).
// Flatter1.mash
import console;
final int CRUSTY = 30;
print("Hi! How old are you? ");
int age = readInt();
1001ICT Introduction To Programming – 2015-2 294
if (age < CRUSTY) {
println("Impossible! You seem so mature.");
} else {
println("Impossible! You could not be a "
+ "day over " + (age - 10) + ".");
}
2. Do the same with three cases.
// Flatter2.mash
import console;
final int SCHOOL_AGE = 5;
final int CRUSTY = 30;
final int ANCIENT = 105;
1001ICT Introduction To Programming – 2015-2 295
print("Hi! How old are you? ");
int age = readInt();
if (age < SCHOOL_AGE || age >= ANCIENT) {
println("Wow! You can type!");
} else if (age < CRUSTY) {
println("Impossible! You seem so mature.");
} else {
println("Impossible! You could not be a "
+ "day over " + (age - 10) + ".");
}
1001ICT Introduction To Programming – 2015-2 296
15.2 One statement or a block?
All of these structured statements include other statements that may or may
not be executed.
whileStatement
statement)orExpression(while
forStatement
statement)forControl(for
doWhileStatement
;)orExpression(whilestatementdo
ifElseStatement
statementelse
statement)orExpression(if
In all cases the statement can and should be a block.
1001ICT Introduction To Programming – 2015-2 297
Here is an example program without braces to make blocks, but good in-
denting.
// EvenOdd1.mash
import console;
print("Enter a number: ");
int i = readInt();
if (i % 2 == 0)
println("Even!");
else
println("Odd!");
1001ICT Introduction To Programming – 2015-2 298
It works well:
$ java EvenOdd1
Enter a number: 23
Odd!
The problem comes when we modify a program later.
// EvenOdd2.mash
import console;
print("Enter a number: ");
1001ICT Introduction To Programming – 2015-2 299
int i = readInt();
if (i % 2 == 0)
println("Even!");
println("That means not odd.");
else
println("Odd!");
It does not compile.
$ mashc EvenOdd2.mash
mashc error: Error on line 8: statement expected.
println("Even!");
println("That means not odd.");
else
ˆ
|
1001ICT Introduction To Programming – 2015-2 300
We can be fooled by the good indenting into believing the structure of the
program is what the indenting shows, but the compiler ignores it.
This example is even worse.
// EvenOdd3.mash
import console;
print("Enter a number: ");
int i = readInt();
if (i % 2 == 0)
println("Even!");
else
println("Odd!");
println("That means not even.");
1001ICT Introduction To Programming – 2015-2 301
It does compile.
$ java EvenOdd3
Enter a number: 42
Even!
That means not even.
If we put the braces in, to make blocks, then when we modify the code later,
we won’t make the mistakes later when we add statements.
1001ICT Introduction To Programming – 2015-2 302
15.3 More about writing ifs
The if case may be empty:
if (rotations >= 0) {
} else {
motorStop(A);
}
The else case may be empty:
if (rotations >= 0) {
motorStop(A);
} else {
}
1001ICT Introduction To Programming – 2015-2 303
The else is optional (although risky to omit):
if (rotations >= 0) {
motorStop(A);
}
You still indent, even if you omit the braces:
if (rotations >= 0)
motorStop(A);
This shows that the statement “belongs” to the if.
1001ICT Introduction To Programming – 2015-2 304
Watch out for extra semicolons!
if (rotations >= 0);
motorStop(A);
Will this compile? Why?
1001ICT Introduction To Programming – 2015-2 305
15.4 Example
As a class, develop a solution to this problem.
1. Write a program that reads exam marks until input is ended by typ-
ing a negative number, then print the highest mark. What should the
program do if the very first input number is negative?
1001ICT Introduction To Programming – 2015-2 306
15.5 Section summary
This section covered:
• the syntax of Java’s main selection statement;
• how to write selections; and
• many tips on good coding practice and style.
1001ICT Introduction To Programming – 2015-2 307
15.6 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 308
15.7 Self-practice exercises
1. Write a program that inputs a person’s height and weight and prints
their body mass index (BMI).
2. Extend your BMI calculation program so that after the BMI is calcu-
lated, it tells the user whether they are underweight, overweight or in
the normal range.
3. Write a program that asks the user to enter a whole number, and then
prints all of the numbers that are factors of that number. (MaSH On-
line: 0113-factors1)
1001ICT Introduction To Programming – 2015-2 309
4. Write a program that asks the user to enter a whole number and then
reports whether that number is:
• even or odd;
• a triangular number or not;
• a square number or not; and/or
• (advanced) a perfect number or not.
1001ICT Introduction To Programming – 2015-2 310
16 Debugging
When programs don’t do what was intended, the process of fixing them is
called debugging.
This section has some general advice about how to debug, and how not to
have to do it.
1001ICT Introduction To Programming – 2015-2 311
16.1 Not bugs – defects
The term “bug” is cute, but implies that they are things that are going to
creep into our programs, no matter what we do.
They should be called defects, and they get there because we put them there.
The best way to make programs without defects is to not make the mistakes
in the first place.
We do that by thinking carefully and designing before we code, and by
testing a lot as we code.
Even so, the best programmers still introduce some defects, albeit less than
novice programmers.
1001ICT Introduction To Programming – 2015-2 312
16.2 Understanding your program
A defect is an instance where what the program
really does is not what was intended.
This implies that we did not really understand
what we created.
To remove the defect, we need to understand the
program better. misunderstood creation
If you change something without really understanding the problem, even if
it seems to fix the problem, chances are you have introduced another defect
that will become apparent later.
While you are learning to program, every bug is an opportunity to under-
stand programs better.
Programmers never stop learning.
1001ICT Introduction To Programming – 2015-2 313
16.3 Reductionism is not a dirty word
Most alternative health practitioners claim scien-
tific medicine is bad because it is reductionist, and
not wholistic.
We are more than the sum of our parts, but the sci-
entific understanding of our parts sure helps under-
stand the whole.
Lucky for us, programs don’t care if you chop
them into little pieces.
person debugger
If you try to think about all of a big program at the same time, you will
never be able to isolate the problem.
1001ICT Introduction To Programming – 2015-2 314
16.4 Test as you code
Never type in all of a big program and only then compile and test.
Type in a few statements, compile, test, understand, debug, and repeat until
done.
If you do this, any defects you find will already be isolated to the last few
lines you typed.
1001ICT Introduction To Programming – 2015-2 315
16.5 Peek inside
If a doctor wants to understand what’s wrong with a patient, she will per-
form tests and scans to find out what’s really going on under the skin.
The programmer’s problem is that we can’t typically watch our programs
run.
Sometimes we can, for example with the MaSH debugger, but what about
when there is no debugger available?
Add extra printing statements to:
• confirm that a location in the code is actually reached; and
• see what values are actually in the variables, and how they change.
On the NXT, display debugging information on the LCD.
1001ICT Introduction To Programming – 2015-2 316
16.6 Isolate with comments
If you have already completed a program, and can’t isolate a problem, par-
ticularly if the program is crashing, use /* ... */ comments to remove
large chunks of your program until the problem goes away.
Then slowly uncomment, line-by-line, until the problem occurs again.
Tip: As /* ... */ comments can’t be nested, mostly use // comments
that can be included inside debugging /* ... */ comments.
1001ICT Introduction To Programming – 2015-2 317
16.7 Don’t be too clever
Write clear code, as if you are expecting to have to debug it. You will.
“Debugging is twice as hard as writing the code in the first
place. Therefore, if you write the code as cleverly as possible,
you are, by definition, not smart enough to debug it.”
– Brian W. Kernighan
“Always code as if the guy who ends up maintaining your code
will be a violent psychopath who knows where you live.”
– Martin Golding
1001ICT Introduction To Programming – 2015-2 318
16.8 Section summary
This section covered:
• bugs as defects and misunderstandings;
• strategies for isolating bugs; and
• strategies for peeking inside the operation of a running program.
1001ICT Introduction To Programming – 2015-2 319
16.9 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 320
17 Handy Math Functions
There are some useful mathematical definitions in all MaSH environments.
This section will define some functions mathematically before showing the
Java functions.
1001ICT Introduction To Programming – 2015-2 321
17.1 Mathematical definitions
17.1.1 Square root
To find the square root of a number is to find the number that if squared
gives you the number you started with.
For example:
√
9 = 3,because 32 = 3 × 3 = 9
But also:
√
9 = −3,because (−3)2 = −3 × −3 = 9
What is
√−9?
1001ICT Introduction To Programming – 2015-2 322
17.1.2 Logarithms
The logarithm to base b of a number x is the exponent to which b has to be
raised to yield x.
So the logarithm is the inverse operation to exponentiation.
If
logb x = y
then
by = x
1001ICT Introduction To Programming – 2015-2 323
Logarithms to base 10 are called common logarithms.
logx = log10 x
Logarithms to base e (Euler’s number, 2.7182818284...) are called natural
logarithms.
lnx = loge x
Logarithms to base 2 are called binary logarithms.
lgx = log2 x
1001ICT Introduction To Programming – 2015-2 324
If you can calculate logarithms to base b, then you can calculate logarithms
to any other base a by
loga x = logb xlogb a
Programming language APIs typically only provide a function to calculate
natural logarithms.
1001ICT Introduction To Programming – 2015-2 325
17.1.3 Absolute value
The absolute value of a number is its magnitude (size), regardless of its sign
(positive or negative).
The absolute value of x is written as ∣x∣.
Example:
∣3∣ = ∣ − 3∣ = 3
1001ICT Introduction To Programming – 2015-2 326
17.1.4 Rounding
Rounding is done when we need to find the whole number that is closest to
a fractional one.
To round x up (towards +∞), use the ceiling of x, ⌈x⌉.
To round x down (towards −∞), use the floor of x, ⌊x⌋.
Examples: ⌈3⌉ = 3, ⌈3.5⌉ = 4, ⌈−3⌉ = −3, ⌈−3.5⌉ = −3,⌊3⌋ = 3, ⌊3.5⌋ = 3, ⌊−3⌋ = −3, ⌊−3.5⌋ = −4.
To round to the nearest whole number, regardless of whether that’s up or
down, add 0.5, then floor. Examples:
⌊3.3 + 0.5⌋ = ⌊3.8⌋ = 3, and ⌊3.8 + 0.5⌋ = ⌊4.3⌋ = 4
1001ICT Introduction To Programming – 2015-2 327
17.2 Java functions
double abs(double a)
Purpose: Returns the absolute value of a.
float abs(float a)
Purpose: Returns the absolute value of a.
long abs(long a)
Purpose: Returns the absolute value of a.
1001ICT Introduction To Programming – 2015-2 328
int abs(int a)
Purpose: Returns the absolute value of a.
double ceil(double a)
Purpose: Returns the least double value that is greater than or
equal to a and equal to an integer.
double floor(double a)
Purpose: Returns the greatest double value that is less than or
equal to a and equal to an integer.
1001ICT Introduction To Programming – 2015-2 329
long round(double a)
Purpose: Returns the closest long to a.
int round(float a)
Purpose: Returns the closest int to a.
double sqrt(double a)
Purpose: Returns the square root of a.
Precondition: a ≥ 0.0.
1001ICT Introduction To Programming – 2015-2 330
double pow(double a, double b)
Purpose: Returns a raised to the power b, ab.
double log(double x)
Purpose: Returns the natural logarithm of x.
double exp(double x)
Purpose: Returns ex, that is Euler’s constant e raised to power
x.
1001ICT Introduction To Programming – 2015-2 331
double max(double a, double b)
Purpose: Returns the greater of a and b.
float max(float a, float b)
Purpose: Returns the greater of a and b.
int max(int a, int b)
Purpose: Returns the greater of a and b.
long max(long a, long b)
Purpose: Returns the greater of a and b.
1001ICT Introduction To Programming – 2015-2 332
double min(double a, double b)
Purpose: Returns the lesser of a and b.
float min(float a, float b)
Purpose: Returns the lesser of a and b.
int min(int a, int b)
Purpose: Returns the lesser of a and b.
long min(long a, long b)
Purpose: Returns the lesser of a and b.
1001ICT Introduction To Programming – 2015-2 333
double random()
Purpose: Returns a random number x such that 0.0 ≤ x < 1.0 .
1001ICT Introduction To Programming – 2015-2 334
17.3 Section summary
This section covered:
• some useful mathematical functions; and
• their definitions in Java.
1001ICT Introduction To Programming – 2015-2 335
17.4 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 336
18 Characters and Strings
This section is about the only data type in MaSH that isn’t simple, like int,
that is the String.
1001ICT Introduction To Programming – 2015-2 337
18.1 Characters
Type char is very similar to type int.
It contains a number.
This number is used to represent a character in the Unicode character set.
It is up to the software that is displaying text to draw the glyph (picture) that
we recognise visually as a character.
A set of glyphs sharing a common visual style is a font.
As a simple (essentially numeric) type, you can use arithmetic and relational
operators (e.g. +, ==) with chars.
1001ICT Introduction To Programming – 2015-2 338
18.2 Strings
String is not simple data type like int or char.
Strings are objects.
That is the reason that the name String starts with an upper case letter.
A String object contains zero or more characters.
Because Strings are not simple values like ints, there are some things
we are used to doing with other types that don’t work with Strings.
1001ICT Introduction To Programming – 2015-2 339
18.3 Operators
As we have seen previously the plus sign operator + works with Strings
as the concatenate operator.
But other operators, particularly the relational operators, don’t work as you
expect with Strings!
The == operator does not look inside two String objects and determine
that all of the characters are indeed equal.
For objects, these tests for equality are provided as functions.
1001ICT Introduction To Programming – 2015-2 340
18.4 String functions
MaSH provides only three simple string functions in most environments.
int length(String s)
Purpose: Returns the length of s.
char charAt(String s, int i)
Purpose: Returns the character at position i in s.
Precondition: 0 ≤ i < length(s).
boolean equals(String a, String b)
Purpose: Returns true if and only if a contains the same se-
quence of characters as in b.
1001ICT Introduction To Programming – 2015-2 341
This is an important function for converting numbers to strings, controlling
the padding and precision. There are others like it for other types.
String format (double d, int w, char f, int p)
Purpose: Returns d converted to a string, padded with spaces
to a minimum width |w|.
If w is negative, the result is left-justified, otherwise right-justified.
f controls the format: ’e’ selects scientific notation; ’f’ se-
lects fixed point; or ’g’ selects the best format depending on
the number and p.
For ’e’ and ’f’, p is the number of decimal digits to display
after the decimal point, but for ’g’ it is the total number of
digits.
1001ICT Introduction To Programming – 2015-2 342
Examples:
call result
format(1234.56789, 12, ’e’, 4) " 1.2346e+03"
format(1234.56789, 12, ’f’, 4) " 1234.5679"
format(1234.56789, 12, ’g’, 4) " 1235"
format(1234.56789, -12, ’e’, 4) "1.2346e+03 "
format(1234.56789, -12, ’f’, 4) "1234.5679 "
format(1234.56789, -12, ’g’, 4) "1235 "
format(0.000001234567, 12, ’e’, 4) " 1.2346e-06"
format(0.000001234567, 12, ’f’, 4) " 0.0000"
format(0.000001234567, 12, ’g’, 4) " 1.235e-06"
Look in the API for functions that convert other types to strings, e.g. long.
1001ICT Introduction To Programming – 2015-2 343
There are obvious omissions in the MaSH API for strings:
• How do you compare strings in ways other than total equality?
• How do you convert a string to upper or lower case?
• How do you extract a part of string (bigger than a single character)?
• How do you search for certain patterns in a string?
These are all things provided in Java, but they make good programming
exercises for us in MaSH.
It’s time we learned how to create our own functions.
1001ICT Introduction To Programming – 2015-2 344
18.5 Section summary
This section covered:
• String is not a simple type;
• operators like == do not work with strings; and
• functions that are provided to work with strings.
1001ICT Introduction To Programming – 2015-2 345
18.6 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 346
18.7 Self-practice exercises
1. Write a program that reads a line of text and reports how many periods
(.) are in the line. (MaSH Online: 0201-countDots)
1001ICT Introduction To Programming – 2015-2 347
19 Compatibility and Conversions
In this section we learn:
• what values may be assigned to what variables;
• how values are sometimes automatically converted to different types;
and
• how to force conversions explicitly.
1001ICT Introduction To Programming – 2015-2 348
19.1 Widening and narrowing
The Java compiler always tries to ensure that information is not lost when a
value is converted from one type to another.
Information might be lost when:
• converting from a type that can represent a wider range of values to
one that can represent only a narrower range of values; or
• converting from a type that can represent fractional numbers to one
that can represent only whole numbers.
The compiler usually permits widening conversions, and tries to prevent
narrowing conversions.
narrow : char → int → long → float → double : wide
1001ICT Introduction To Programming – 2015-2 349
19.2 Type compatibility
Loosely, a value is compatible with a variable we want to put it in, if:
• it is the same type as the variable; or
• can be converted to the variable’s type by a widening conversion.
1001ICT Introduction To Programming – 2015-2 350
This example program compiles.
// Widen.mash
import console;
long a = 0; // int to long conversion
float b = 0; // int to float conversion
float c = 0L; // long to float conversion
double d = 0.0F; // float to double conversion
All the conversions are widenings.
1001ICT Introduction To Programming – 2015-2 351
No statement of this example program compiles.
// Narrow1.mash
import console;
int a = 0L; // long to int conversion
int b = 0.0F; // float to int conversion
long c = 0.0F; // float to long conversion
float d = 0.0; // double to float conversion
All the conversions are prohibited narrowings.
1001ICT Introduction To Programming – 2015-2 352
19.3 Type coercions
Type coercion is the implicit (hidden, not explicit) conversion of values from
one type to another.
Every conversion example in Widen.mash, above, was a coercion.
19.3.1 Mixed-mode arithmetic
Mixed-mode arithmetic expressions contain values of different types.
Example: 1 + 2.0
In situations like this, the value with the narrower type is coerced to the
wider type before the values are combined with the operator.
1001ICT Introduction To Programming – 2015-2 353
19.4 Type casts
Type casts are explicit, forced conversions from one type to another.
They make narrowing conversions possible.
A cast is written by writing the desired type in parentheses.
This behaves like a unary operator with a very high precedence.
1001ICT Introduction To Programming – 2015-2 354
This example program compiles.
// Narrow2.mash
import console;
int a = (int) 0L; // long to int cast
int b = (int) 0.0F; // float to int cast
long c = (long) 0.0F; // float to long cast
float d = (float) 0.0; // double to float cast
All of the conversions are still narrowings, but they are now permitted as
we have explicitly cast them.
1001ICT Introduction To Programming – 2015-2 355
19.5 Section summary
This section covered:
• type compatibility;
• type coercions; and
• type casts.
1001ICT Introduction To Programming – 2015-2 356
19.6 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 357
20 Packaging What Happens In Methods
This section takes us to the next MaSH level: methods.
A method is either a procedure or a function.
You have already been calling methods defined by the MaSH environments.
In this section you learn to write your own.
1001ICT Introduction To Programming – 2015-2 358
20.1 Why use methods
In all programming languages we encapsulate statements into small pack-
ages called variously “subroutine”, “procedures”, “functions”, or “meth-
ods”.
We do this for three main reasons:
1. for reuse;
2. to minimize the number of defects (bugs) by simplifying a program;
and
3. as another way to control the flow of execution in a program.
1001ICT Introduction To Programming – 2015-2 359
20.1.1 Reuse
If we can identify a group of statements that carry out an action that we
want to perform more than once in a program, it is better to package those
statements in a method. The overall program will be smaller and easier to
maintain.
We may be able to reuse a method in another program.
Cohesion (how well the parts stick together) is an important property of
methods.
A method with a single well-defined purpose is more likely to be reusable.
1001ICT Introduction To Programming – 2015-2 360
20.1.2 Minimizing Defects
As jobs get more complex, the people doing them make more errors.
The more statements and variables you have to take into account at the same
time, the more likely you are to make errors.
To solve big problems we use the divide and conquer strategy.
Large programs broken down into many methods will be easier to build
with fewer defects, and also easier to understand later as the program is
maintained.
Methods should rarely contain more than about 20 statements.
1001ICT Introduction To Programming – 2015-2 361
20.1.3 Flow control
The flow of control of a program can be deviated from the normal sequence
by using loops and selections, as we have already been doing.
Calling a method also alters the flow of control.
Methods can call themselves (recursion). This is a way to get repetition in
a program without writing loops.
Methods you write with predefined names can be called by the system in
response to external events. This is how:
• programs are started;
• programs can be made to do multiple things at once; and
• user events like mouse clicks can be handled.
1001ICT Introduction To Programming – 2015-2 362
20.2 The syntax of programs with methods
Most of the grammar as presented for the statements and control levels is
unchanged, except for the parts relating to how code is encapsulated, and
there is one new structured statement.
1001ICT Introduction To Programming – 2015-2 363
20.2.1 MaSH programs
A program still begins with an import directive that selects the environment
within which this program will run. After the import directive comes the
program: in the no-method program structure (as before); or in the method
program structure (new).
mashProgram
noMethodProgram
methodProgram
importDirective
From now on we shall always use the method program structure.
1001ICT Introduction To Programming – 2015-2 364
20.2.2 Method programs
A method program consists of a sequence of top-level declarations.
At the top level we declare global variables, global constants and methods.
methodProgram
topLevelDeclaration
1001ICT Introduction To Programming – 2015-2 365
20.2.3 Top-level declarations
In a method program, we make a series of top-level declarations.
At the top level we can declare and initialise variables and constants, and
declare methods.
All of the other kinds of statements must now be encapsulated within meth-
ods.
topLevelDeclaration
declarationStatement
methodDeclaration
1001ICT Introduction To Programming – 2015-2 366
20.2.4 Method declarations
A method declaration has two parts, a heading followed by a block that will
encapsulate the statements that perform the actions of the method.
methodDeclaration
blockmethodHeader
Recall that a block is a sequence of statements enclosed within braces.
block
}
statement
{
1001ICT Introduction To Programming – 2015-2 367
20.2.5 Method headers
The method header starts with either the type that the method will return
(making the method a function) or void (making the method a procedure).
Then follows the name of the method and then the formal parameter list.
methodHeader
formalParameterListidentifiervoid
type
You have already seen method headers in the documentation for the MaSH
environments. Example:
double pow(double a, double b)
1001ICT Introduction To Programming – 2015-2 368
20.2.6 void
A void declaration consists only of the keyword void.
void
void
20.2.7 Formal parameter lists
A formal parameter list is a sequence of zero or more formal parameter
declarations separated by commas and enclosed in parentheses.
formalParameterList
)
formalParameter,
formalParameter
(
1001ICT Introduction To Programming – 2015-2 369
20.2.8 Formal parameters
A formal parameter declaration consists of the type of the parameter and
introduces a name for this parameter.
formalParameter
identifiertype
1001ICT Introduction To Programming – 2015-2 370
20.2.9 Structured statements
A structured statement now consists of all of the kinds of structured state-
ments previously described, with the addition of the return statement.
structuredStatement
block
whileStatement
forStatement
doWhileStatement
ifElseStatement
returnStatement
1001ICT Introduction To Programming – 2015-2 371
20.2.10 return statements
A return statement consists of the keyword return, followed optionally
by an expression, and then a semicolon.
returnStatement
;
orExpression
return
If the enclosing method is a function the expression should be there. It is
the value returned by the function.
If the enclosing method is a procedure, there is no expression. The return
statement’s only purpose is to exit the procedure.
1001ICT Introduction To Programming – 2015-2 372
20.3 The main method
A program starts when the operating system calls the main method of a
program.
The main method of a MaSH program must be a procedure with this head-
ing:
void main()
That is, it must be a procedure, called main with no arguments.
1001ICT Introduction To Programming – 2015-2 373
Here is the Hello program rewritten with a main method.
import console;
void main() {
println("Hello, World!");
}
Note how the statement in the method’s block is indented, just as we do
with all blocks in structured statements.
1001ICT Introduction To Programming – 2015-2 374
20.4 An example procedure: waitForDark
This procedure already exists in the nxt environment, but if it didn’t we
could write it.
void waitForDark(int port, int light)
Purpose: Makes the program wait until the light sensor reading
on port is at most the desired light level.
Waiting means doing nothing while what you are waiting for hasn’t hap-
pened.
void waitForDark(int port, int light) {
while (getLight(port) > light) {
}
}
1001ICT Introduction To Programming – 2015-2 375
20.5 An example function: min
This function already exists in most MaSH environments, but if it didn’t...
int min(int a, int b)
Purpose: Returns the lesser of a and b.
int min(int a, int b) {
if (a < b) {
return a;
} else {
return b;
}
}
1001ICT Introduction To Programming – 2015-2 376
20.6 Important rules
• There should be a blank line between all top level declarations, except
between closely related constants or variables.
• Since the statements inside a method are enclosed in a block, they
should be indented within the braces.
• You can’t define a method inside another method. You can call a
method with a statement inside another method.
• Constant and variable initialisations outside of methods are performed
before main is called.
1001ICT Introduction To Programming – 2015-2 377
20.7 Local and global variables and scope
We can declare variables and constants inside or outside of methods.
A variable that is declared inside a method is local to that method, like any
variables declared in a block.
Variables declared outside of all methods (inside a class) are global. Local
variables can’t be referred to from anywhere but within the block they are
declared in.
Global variables can be accessed from any method.
Global variables are one way that methods can share information.
The scope of the variable is the region within the program where the vari-
able is visible.
1001ICT Introduction To Programming – 2015-2 378
20.8 Scope and Lifetime
The lifetime of a variable (and therefore the information in it) is defined by
its scope.
Global variables exist as long as the program is running.
Local variables come into existence when a method starts and vanish when
the method exits.
1001ICT Introduction To Programming – 2015-2 379
20.9 Use global variables sparingly
If you want to copy a method from one program to another (one way to
reuse it), don’t make it depend on global variables.
The right way to share information with a reusable method is via its param-
eters.
If you want to make programs simpler and easy to understand and debug,
don’t make your methods depend on global variables too much.
If your methods have a lot of subtle interactions via shared global variables,
they can’t be thought about separately. Make the information transfer ex-
plicit via parameters.
On the other hand, global variables that are needed by a lot of methods, and
don’t change after some initial set-up (almost like constants) are perfectly
OK, and are preferred over every method having to pass around the same
parameters, over and over.
1001ICT Introduction To Programming – 2015-2 380
20.10 Overloading
We can overload a method’s name by using it for more than one method.
Each method must have different parameter lists.
They must be different with respect to the types (the names don’t matter).
For example, we have all of these:
int min(int a, int b)
long min(long a, long b)
float min(float a, float b)
double min(double a, double b)
1001ICT Introduction To Programming – 2015-2 381
20.11 Parameter passing: by value
Programming language designers have a range of choices as to how infor-
mation may be passed to methods via their parameters.
The choices are mostly between:
passing by value A copy of the value of the actual parameter is passed to
the method’s formal parameter.
Java always does this.
Any changes to the formal parameter made within the method have
no effect on the actual parameter.
passing by reference A reference to the actual parameter, which must be a
variable, is passed to the formal parameter.
Changes to the formal parameter do affect the actual parameter!
1001ICT Introduction To Programming – 2015-2 382
While Java always passes by value, some variables are actually references.
All variables with object types, like String, and arrays (later) are refer-
ences.
So in these cases, passing a value means that a reference is being passed.
Even so, since there is no way to change what is in a String object,
Strings passed as parameters will not be changed by any method.
Arrays can be changed if passed as parameters.
Aside from arrays, the best way that a method can return information to its
caller is by being a function that returns a result.
1001ICT Introduction To Programming – 2015-2 383
20.12 Passing and scope examples
Run this program with the debugger.
// ByValue1.mash
import console;
void main() {
int i = 0;
println("In main, i = " + i);
bump(i);
println("In main, i = " + i);
i = inc(i);
println("In main, i = " + i);
}
1001ICT Introduction To Programming – 2015-2 384
void bump(int j) {
println("In bump, j = " + j);
j = j + 1;
println("In bump, j = " + j);
}
int inc(int k) {
println("In inc, k = " + k);
k = k + 1;
println("In inc, k = " + k);
return k;
}
What effect does changing a formal parameter have on the actual parame-
ter?
1001ICT Introduction To Programming – 2015-2 385
Run this second version with the debugger.
// ByValue2.mash
import console;
void main() {
int i = 0;
println("In main, i = " + i);
bump(i);
println("In main, i = " + i);
i = inc(i);
println("In main, i = " + i);
}
1001ICT Introduction To Programming – 2015-2 386
void bump(int i) {
println("In bump, i = " + i);
i = i + 1;
println("In bump, i = " + i);
}
int inc(int i) {
println("In inc, i = " + i);
i = i + 1;
println("In inc, i = " + i);
return i;
}
What effect does using the same names for the formal parameters as the
actual parameters have?
1001ICT Introduction To Programming – 2015-2 387
Run this program with the debugger.
// LocalGlobal.mash
import console;
int g = 0, h = 0;
void main() {
int h = 0;
println("In main, g = " + g + ", h = " + h);
g = g + 1;
h = h + 1;
println("In main, g = " + g + ", h = " + h);
}
What happens when a global variable and a local variable share a name?
1001ICT Introduction To Programming – 2015-2 388
20.13 Character and string examples
This program includes a function that converts a single character to upper
case and another that converts a whole string.
The main function’s purpose is just to test these functions.
Take note of the format of the comment that precedes each function.
The comment needs to specify what this function does so that it may be
called again, but it does not need to say how it works.
// ToUpperCase1.mash
import console;
1001ICT Introduction To Programming – 2015-2 389
// toUpperCase(c) returns c converted to upper
// case if it is a lower case letter, or c
// unchanged otherwise.
char toUpperCase(char c) {
if (’a’ <= c && c <= ’z’) {
return (char) (c - ’a’ + ’A’);
} else {
return c;
}
}
This works because all the upper case letters appear in sequence in the Uni-
code character set, as do the lower case letters, in the same order.
Performing arithmetic with chars results in an int.
The int result needs to be cast back to a char.
1001ICT Introduction To Programming – 2015-2 390
// toUpperCase(s) returns s converted to upper
// case.
String toUpperCase(String s) {
String t = "";
for (int i = 0; i < length(s); i = i + 1) {
t = t + toUpperCase(charAt(s, i));
}
return t;
}
1001ICT Introduction To Programming – 2015-2 391
void main() {
println(toUpperCase(’a’));
println(toUpperCase(’b’));
println(toUpperCase(’z’));
println(toUpperCase(’A’));
println(toUpperCase(’;’));
println(toUpperCase(’9’));
println(toUpperCase(""));
println(toUpperCase("a"));
println(toUpperCase("abzA;9"));
}
Run this with the debugger, and watch as the parameters and local variables
come and go.
Note that the last variable to be added is the first that will disappear.
Variables are stored in a last-in-first-out stack.
1001ICT Introduction To Programming – 2015-2 392
20.14 Section summary
This section covered:
• why we use methods: reuse; simplification; flow control;
• the syntax of programs with methods;
• the main method starts a program;
• scope and lifetime;
• parameter passing by value; and
• lots of examples and advice.
1001ICT Introduction To Programming – 2015-2 393
20.15 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 394
20.16 Self-practice exercises
1. Write a program that reads a line of text and reports how many deci-
mal digits are in the line. As part of this program write a function that
determines whether a character parameter is a digit or not. (MaSH
Online: 0202-countDigits1)
2. Write a program that reads all of standard input and for each line
reports how many decimal digits are in the line. Reuse your function
from the previous exercise. (MaSH Online: 0203-countDigits2)
3. Write a program that reads all of standard input and prints all the lines
of input reversed, so the left-most character becomes the right-most.
Write a reversing function.
4. Write a function that calculates the monthly repayment on a loan, and
a program that reads the required inputs and calls it to print the result.
The required formulas are:
1001ICT Introduction To Programming – 2015-2 395
monthly interest rate = r = rannual
12 × 100
monthly repayment = R = A r
1 − (1 + r)−n
where A is the loan amount to be paid off over n months.
1001ICT Introduction To Programming – 2015-2 396
5. Write a function that tests whether a character occurs in a string. For
example, return true because ’l’ occurs in "Hello!".
6. Write a function that returns the left-most position that a character
occurs in a string. If the character does not occur, return the length of
the string.
7. Write a program that includes a procedure that prints an empty box
like this:
> java Box
Enter the width: 10
Enter the height: 5
+--------+
| |
| |
| |
+--------+
1001ICT Introduction To Programming – 2015-2 397
>1001ICT Introduction To Programming – 2015-2 398
8. A carpet store wants a program that will quote the cost of carpeting
a rectangular room. Carpet comes in rolls that are 4.5 metres wide.
The customer pays for carpet per metre of the roll used. The customer
pays that full price even if the full width of the roll is not used. It may
be cheaper to lay the carpet in strips running one way than another,
because there is less wastage.
Write a program that returns the cheapest price to carpet a room given
the length and width of the room in metres and the price in dollars per
metre of carpet. The width of a roll (4.5 m) should be defined as a
symbolic constant. Writing a function that does the calculation either
way makes the program much simpler.
1001ICT Introduction To Programming – 2015-2 399
21 Geometry For Graphics
This section discusses coordinate systems, some maths functions, and the
MaSH graphics environment.
1001ICT Introduction To Programming – 2015-2 400
21.1 Coordinate systems
21.1.1 Cartesian coordinates
A Cartesian coordinate system locates points on
a 2-dimensional plane or in a 3-dimensional space
using distances along mutually perpendicular (or-
thogonal) axes.
Where the axes meet is called the origin.
Also known as rectangular coordinates.
(x,y)
y
x
(x,y,z)
y
x
z
1001ICT Introduction To Programming – 2015-2 401
21.1.2 Cartesian coordinates in computer graphics
Some graphics environments, e.g. PostScript and
PDF, put the origin at the bottom-left of the page,
so the axes have the conventional orientation.
(x,y)
y
x
However, most screen graphical environments,
e.g. Java and Flash, put the origin at the top-left,
and increasing y values mean lower.
(x,y)
y
x
1001ICT Introduction To Programming – 2015-2 402
21.1.3 Polar coordinates
The 2-dimensional polar coordinate system lo-
cates points on 2-dimensional plane using the dis-
tance from the origin, r, and an angle θ from the
positive x axis.
r
1001ICT Introduction To Programming – 2015-2 403
21.2 Angles
For robotics and graphics we often use an-
gles.
Most people (and graphics programming en-
vironments) use degrees of arc.
Most mathematicians (and mathematical
programing environments) use radians.
To convert:
radians = pi × degrees
180
degrees = 180 × radians
pi
360°
90°
degrees
2pi
pi/2
radians
1001ICT Introduction To Programming – 2015-2 404
21.3 Trigonometric functions
The trigonometric or circular functions relate angles to lengths.
They are defined by any right-angled triangle.
y
x
r
Sine ∶ sin θ = y
r
Cosine ∶ cos θ = x
r
Tangent ∶ tan θ = y
x
These functions have inverses that return angles:
sin−1 = arcsin; cos−1 = arccos; tan−1 = arctan .
1001ICT Introduction To Programming – 2015-2 405
To convert from polar to rectangular coordinates:
x = r cos θ; y = r sin θ.
To convert from rectangular to polar coordinates:
r = √x2 + y2; θ = atan2(y, x)
where atan2 is a special version of arctan that uses both x and y to return
the angle θ in the correct quadrant and avoids division by zero if x = 0.
All of these functions appear in the Java (and MaSH) APIs.
1001ICT Introduction To Programming – 2015-2 406
21.4 The graphics environment
The MaSH environment, graphics, contains all the input and output
methods from console, plus methods for drawing in a window.
Graphics programs must be organised into methods.
All drawing must be done in a procedure paintWindow().
This method is called by the system whenever it decides the window’s con-
tents need to be drawn or redrawn.
It will be redrawn if the window is resized, or many times if the program
uses animation.
The paintWindow() method, or any method it calls must not do any
reading from the keyboard (or anywhere) as it must be fast.
For this reason also, the MaSH debugger will not step slowly through the
paintWindow() method or any method it calls.
1001ICT Introduction To Programming – 2015-2 407
21.4.1 Setting up the window
A graphics program must have a main method, as normal.
void main()
In main, the program should usually read any input data before putting up
the window.
To put up the window, first call:
void setFrameSize(int width, int height)
Purpose: Sets the size of the window with width and height.
Then call:
void setFrameVisible(boolean visibility)
Purpose: Set the visibility of the window. true means
visible.
1001ICT Introduction To Programming – 2015-2 408
Note that main does not call paintWindow() directly.
The system will do that when the window is put up.
If you want to force it to be painted again, call:
void repaint()
Purpose: Causes the window to be repainted.
For repeated repaints, for animation, call:
void animate(int fps)
Purpose: Causes the window to be repainted at fps frames per
second. Only call this method once.
Precondition: fps > 0.
1001ICT Introduction To Programming – 2015-2 409
21.4.2 Drawing
The following methods may only be called from the paintWindow()
method or methods called from that.
They provide drawing of simple shapes (primitives), out of which complex
figures may be created.
There are more. See the graphics environment documentation.
void drawLine(int x1, int y1, int x2, int y2)
Purpose: Draw a line.
void drawRect(int x, int y, int width, int height)
Purpose: Draws the outline of the specified rectangle.
1001ICT Introduction To Programming – 2015-2 410
void fillRect(int x, int y, int width, int height)
Purpose: Fills the specified rectangle.
void drawString(String s, int x, int y)
Purpose: Draw a string.
void setColor(int red, int green, int blue)
Purpose: Set the colour to draw with by defining the amounts
of (red, green, blue). (0,0,0) is black. (255,255,255) is
white.
Precondition: 0 ≤ red ≤ 255; 0 ≤ green ≤ 255; and 0 ≤ blue≤ 255.
1001ICT Introduction To Programming – 2015-2 411
21.4.3 Examples
Demonstrate this example program.
/*
** file: RedBox1.mash
** purpose: Puts up a window and
** draws a red box in it.
*/
import graphics;
void main () {
setFrameSize(200, 220);
setFrameVisible(true);
}
1001ICT Introduction To Programming – 2015-2 412
void paintWindow() {
setColor(255, 0, 0);
fillRect(50, 50, 100, 100);
}
1001ICT Introduction To Programming – 2015-2 413
Demonstrate this example program with the debugger.
/*
** file: RedBox2.mash
** purpose: Puts up a window and draws
** an animated red box in it.
*/
import graphics;
void main () {
setFrameSize(200, 220);
setFrameVisible(true);
animate(10);
}
1001ICT Introduction To Programming – 2015-2 414
int x = 50, y = 50; // box coords
void paintWindow() {
setColor(255, 0, 0);
fillRect(x, y, 100, 100);
x = x + (int) (random() * 5) - 2;
y = y + (int) (random() * 5) - 2;
}
1001ICT Introduction To Programming – 2015-2 415
21.5 Section summary
This section covered:
• coordinate systems;
• angle conversions;
• some useful mathematical functions; and
• the graphics environment.
1001ICT Introduction To Programming – 2015-2 416
21.6 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 417
22 Arrays
22.1 What are arrays?
Arrays are the most basic way a program can be made to work with lots of
information.
An array is a collection of data values (elements) all of the same type.
We can refer to any particular element within an array by its index number.
Indices are always whole numbers starting at 0.
  42  -7  23   0 100  
   0   1   2   3   4  
Arrays may be very large, so for efficiency the way we refer to arrays is
different to the way we refer to ordinary variables.
1001ICT Introduction To Programming – 2015-2 418
22.2 Parameter passing by value
Nearly all programs are divided up into many methods.
Methods send each other information by passing parameters.
void main() {      void printPlus1(int i) {
   int i = 42;        i = i + 1;
   printPlus1(i);     println(i);
   println(i);     }
}  
passing a copy of the value in i
What does the above code print?
It would be very inefficient to pass copies of whole arrays around.
1001ICT Introduction To Programming – 2015-2 419
22.3 Array references
The solution to avoiding passing around copies of the whole array, is to only
pass around references.
References are a small piece of information that can be passed around
quickly.
A reference is actually the address in RAM where the array starts.
  42  -7  23   0 100  
Some older languages (particularly C) have pointers.
Pointers are references that you can treat like numbers and do arithmetic
with them and access anywhere in RAM with them.
References are restricted in what you can do with them for very good secu-
rity reasons.
1001ICT Introduction To Programming – 2015-2 420
22.4 The syntax of arrays
22.4.1 Types
The data types are now divided into the array types and the types that are
permitted to be the elements of arrays. Note that arrays can be elements of
arrays, by using multi-dimensional arrays.
type
arrayType
elementType
elementType
simpleType
objectType
The element types include all of the data types except arrays – all of the
simple types (int, double, ...) and all of the compound types (in MaSH
that is just String).
1001ICT Introduction To Programming – 2015-2 421
An array type is written as the type of the element, followed by a pair of
brackets for each dimension of the array.
arrayType
][elementType
Example types:
int the type of a single ordinary integer
int[] the type of a reference to a one-dimensional array of integers
int[][] the type of a reference to a two-dimensional array of integers
String the type of a reference to a string object
String[] the type of a reference to a one-dimensional array of references
to string objects.
When it seems we declare a variable to be an array or String, we are
actually only declaring a reference.
1001ICT Introduction To Programming – 2015-2 422
22.4.2 Initialising constants and variables
The syntax for the introductions of new variables and constants changes
because there is a special kind of expression for arrays that may only be
used in variable and constant declarations.
variableDeclaration
newVariable,
newVariabletype
newVariable
variableInitialiser=
identifier
variableInitialiser
orExpression
arrayInitialiser
1001ICT Introduction To Programming – 2015-2 423
An array initialiser is a list of comma separated variable initialisers, en-
closed in braces. This creates a new array of these values, just big enough
to hold those values.
arrayInitialiser
}
,
variableInitialiser,
variableInitialiser
{
Example:
int[] myArray = {42, -7, 23, 0, 100};
  42  -7  23   0 100myArray
1001ICT Introduction To Programming – 2015-2 424
The new variable myArray is a reference to this new array.
22.4.3 Expressions
There are two new kinds of atomic expressions:
• An array allocation repre-
sents a new array, allocated in
memory and with all its ele-
ments equaling zero (or some
value like zero that makes
sense for the type of ele-
ment).
• An array access is an expres-
sion that refers to an element
of an array.
atomicExpression
literal
arrayAccess
arrayAllocation
identifier
methodInvocation
)orExpression(
1001ICT Introduction To Programming – 2015-2 425
22.4.4 Array allocations
An array allocation is written with the keyword new followed by the ele-
ment type and then a pair of brackets for each dimension of the array. At
least one of the left-most pairs of brackets must have an integral value in
them that declares the size of the array.
arrayAllocation
][
]orExpression[elementTypenew
Example:
int[] myArray = new int[5];
   0   0   0   0   0myArray
1001ICT Introduction To Programming – 2015-2 426
22.4.5 Array accesses
An array access starts with the name of the array variable followed by pairs
of brackets, each containing the integral index number of the element being
selected along each of the array’s dimensions.
arrayAccess
]orExpression[identifier
Array accesses can be put in expressions, and also on the left-hand sides of
assigments.
leftHandSide
arrayAccess
identifier
1001ICT Introduction To Programming – 2015-2 427
Examples:
int[] myArray = new int[5];
   0   0   0   0   0myArray
myArray[1] = 53;
   0  53   0   0   0myArray
   0   1   2   3   4  
for (int i = 0; i < 5; i = i + 1) {
println(myArray[i]);
}
1001ICT Introduction To Programming – 2015-2 428
22.5 Strings are not arrays, but...
You can make arrays of characters, but instead we use Strings.
In Java, Strings are objects.
Objects are compound data types, made up of simpler data types.
Inside every String object, there is an array of characters.
Objects are also accessed via references.
This is why == can’t be used with Strings – it would compare the refer-
ences not the characters in the Strings.
In the description of arrays above, we have completed the full definition of
the MaSH language, a subset of the Java language.
There will not be any more additions to MaSH, because the next logical
step would be to add objects, and for that, Java is simple enough.
1001ICT Introduction To Programming – 2015-2 429
22.6 Section summary
This section covered:
• arrays;
• array references; and
• the syntax for declaring, creating and using arrays.
1001ICT Introduction To Programming – 2015-2 430
22.7 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 431
22.8 Self-practice exercises
1. Change output from the example to
a histogram bar chart.
5 |####
|######
4 |##########
|############
3 |#############
|##########
2 |######
|#######
1 |###
|
0 |#
-----+-------------
mark | frequency
1001ICT Introduction To Programming – 2015-2 432
2. Use the graphics environment to draw a much prettier bar or column
chart.
1001ICT Introduction To Programming – 2015-2 433
3. (Advanced) Print the his-
togram with columns like
this.
There are two strategies:
(a) Use only two for
loops, and a lot of if
statements (probably
the best method); and
(b) Create a two-
dimensional array
of characters to “draw”
into before printing it.
Pick one!
| #
| # #
| # #
| # # # #
f | # # # #
r | # # # #
e | # # # # #
q | # # # # # # #
u | # # # # # # #
e | # # # # # # # #
n | # # # # # # # # #
c | # # # # # # # # #
y |# # # # # # # # # #
+---------------------
0 1 2 3 4 5
mark
1001ICT Introduction To Programming – 2015-2 434
23 About Programming Languages
The story of programming languages is the story of humans inventing ways
to make stuff happen.
We can do things ourselves, but we much prefer it if the things we want
done are done by somebody else.
Getting other people to do them is expensive. (Slavery is frowned upon in
most places these days.)
So getting things done by machines has always been very attractive.
1001ICT Introduction To Programming – 2015-2 435
23.1 Programmable machines
Most machines are essentially single purpose. Whatever they do, they do it
the same way every time.
In 1801 the Jacquard loom was invented. It wove different complicated
patterns according to the holes punched in a series of boards strung together.
This machine was programmable.
A music box and a player piano are programmable in much the same way.
A modern electronic computer isn’t fundamentally different. It performs
simple actions requested by a sequence of instructions stored in memory.
1001ICT Introduction To Programming – 2015-2 436
23.2 5 Generations of Programming Languages
This is one way to classify programming languages.
23.2.1 Generation 1: Machine code
The first computers (of the late 1940s – early 1950s) were programmed at a
level not much higher than punching holes in the Jacquard loom cards, by
flicking switches or plugging and unplugging wires. This was:
• literally coding in 1s and 0s;
• very error prone;
• extremely tedious and expensive.
1001ICT Introduction To Programming – 2015-2 437
23.2.2 Generation 2: Assembly languages
In the 50s the first real programming language was invented: assembly
language.
A programming language is defined as a notational system for describing
computation in a machine-readable and human-readable form.
Assembly language is a textual representation of the actual instructions of
a specific computer.
It is:
• Coding in mnemonic symbols e.g. LDAA (Load Accumulator A)
• More programmer friendly
• Still tedious to use and modify.
1001ICT Introduction To Programming – 2015-2 438
Example (for Motorola 68000, on an original Mac):
CODE
WITH stackFrame
link A6,#localSize
movem.l A1-A5/D0-D7,-(SP)
clr.l D7
movea.l trBuffer(A6),A0
movea.l lo(A6),A1
movea.l hi(A6),A2
move.w (A0)+,D0
and.l #1,D0
add.l startBin(A6),D0
add.l A0,D0
Not exactly readable.
1001ICT Introduction To Programming – 2015-2 439
23.2.3 Generation 3: “High-level” languages
An assembler does a simple one-to-one translation of the instructions, but a
high-level programming language is quite unlike the actual machine codes.
There is much more emphasis on human readability.
It takes a much more sophisticated program to process; either a compiler to
translate or an interpreter to execute.
• Early: Fortran, COBOL
• Later came: ALGOL, BASIC, Pascal, C
• Recent: C++, Java and C#
1001ICT Introduction To Programming – 2015-2 440
There have been two major developments in third generation programming
languages:
Structured programming
Early versions of Fortran and BASIC were very simple, the equivalent of
for loops, but no while loops.
Indefinite loops were coded with selections (ifs) and goto statements.
With a goto statement the program could be made to jump to any other
statement.
Structured statements like whilewere introduced with ALGOL, and made
popular in Pascal and C.
1001ICT Introduction To Programming – 2015-2 441
Object orientation
As programs get larger, the complexity increases dramatically.
As with encapsulation in methods, encapsulation in objects helps manage
this complexity.
Objects enclose both some data and all of the operations that are permitted
upon it.
There are pure object oriented languages where all data is in objects, and
all operations are methods of those objects; e.g. SmallTalk.
But the most popular languages are like Java and C++, hybrids where some
data is in simple types like int, and some in objects.
With MaSH we are learning the non-object oriented elements of Java.
1001ICT Introduction To Programming – 2015-2 442
23.2.4 Generation 4
Generations 4 and 5 are not well defined, but include:
• Specialised languages embedded in applications: ActionScript,
JavaScript, Excel;
• Graphical languages: LabView; Robolab Inventor; and
• Declarative languages: Structured Query Language (SQL), Haskell,
Lisp, Prolog.
23.2.5 Generation 5
• Languages associated with expert systems and Artificial Intelligence;
and
• so much vapourware!
1001ICT Introduction To Programming – 2015-2 443
23.3 Programming paradigms
This is another way to classify programming languages.
The paradigm is the basic computational model that is embodied by a pro-
gramming language.
Here are the major paradigms.
1001ICT Introduction To Programming – 2015-2 444
23.4 The imperative/procedural paradigm
This is the obvious and familiar kind of programming model that is embod-
ied by machine language, assembly language, and high-level languages like
C, Pascal, and MaSH.
Programs are basically sequences of commands (imperatives).
23.5 Pure object-oriented programming
All data in a program is encasulated in objects that send each other messages
(by calling each other’s methods).
23.6 imperative/object-oriented hybrids
Like C++, Java, JavaScript, ActionScript, C#.
1001ICT Introduction To Programming – 2015-2 445
23.7 Functional programming
In these languages, which are more closely related to mathematics than
imperative languages, programs are defined as pure functions.
There are no assignment statements.
Once a variable gets a value, it does not change.
Examples: Scheme; Haskell; Scala (which runs in the Java virtual ma-
chine), F#.
23.8 Logic programming
Programs are defined by facts and rules that establish relationships.
Examples: Prolog; Mercury.
Very popular for artificial intelligence/expert systems.
1001ICT Introduction To Programming – 2015-2 446
23.9 Section summary
This section covered:
• The 5 generations of programming languages; and
• the major programmimg paradigms.
1001ICT Introduction To Programming – 2015-2 447
23.10 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 448
24 Threads
In this section we will introduce threads.
A new doorbell example will perform two tasks in parallel, using threads.
1001ICT Introduction To Programming – 2015-2 449
24.1 NXT threads
A program that needs to do more than one thing simultaneously can use
multiple threads of execution.
The MaSH environment nxt provides up to 5 threads in addition to the
main thread that starts when a program starts. (All programs have at least
one thread, the main thread.)
1001ICT Introduction To Programming – 2015-2 450
How to write a program that uses two threads:
1. Import environment nxt.
2. Your program has a main method as usual. This is the main thread.
3. Write a run1 method. This is the second thread.
4. The program starts as usual with the main method. When you want
the second thread to start, call the method start1(). Do not call
your run1 method directly, that won’t actually start it running as a
second thread. Only call start1 once!
To start a third thread, Write a run2 method, and call start2. And so
on...
1001ICT Introduction To Programming – 2015-2 451
The following is the skeleton of a 2-threaded program:
import nxt;
void main() {
// Do any set-ups you want done before the
// second threads starts here.
start1(); // Start the second thread.
// The actions performed by the main thread
// go here.
}
void run1() {
// The actions performed by the second
// thread go here.
}
1001ICT Introduction To Programming – 2015-2 452
24.2 Doorbell with a scrolling message
A simple two-thread example.
// Doorbell2.mash
// Doorbell with a scrolling message,
// using threads.
import nxt;
final int TOU = 1; // Touch sensor port
1001ICT Introduction To Programming – 2015-2 453
// Multi-line message to scroll up the screen.
String[] message = {
" Welcome ",
" ",
"NO: ",
" salespersons, ",
" hawkers, ",
" proselytizers,",
" beggars, ",
" politicians, ",
" thieves, ",
" relatives, ",
" otherwise...",
" "
};
final int LENGTH = 12;
1001ICT Introduction To Programming – 2015-2 454
void main() {
setUpSensor(TOU, TOUCH);
start1();
while (true) {
waitForPush(TOU);
playNote(XYLOPHONE, 880, 400);
pause(200);
playNote(XYLOPHONE, 440, 600);
}
}
1001ICT Introduction To Programming – 2015-2 455
void run1() {
int i = 0;
while(true) {
drawString(message[i], 0, LCD_LINES - 1);
sleep(1000);
scroll();
i = (i + 1) % LENGTH;
}
}
This program is demonstrated in this movie.
1001ICT Introduction To Programming – 2015-2 456
24.3 Section summary
This section covered:
• threads in the nxt environment.
1001ICT Introduction To Programming – 2015-2 457
24.4 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 458
25 Events
In this section we will introduce event handling.
A revised doorbell example will use events, and implictly the event dispatch
thread, rather than create its own second thread.
1001ICT Introduction To Programming – 2015-2 459
25.1 Events
25.1.1 Polling
Programs that must wait for something to happen, for example user input,
are very common.
The earliest way to do this was to continually poll the source of input to see
if any was available.
If the program has to be doing other things in the meantime, the need to
interleave the polling with the other actions leads to very complicated code.
25.1.2 Threads
One way to simplify such code is to separate the polling and the other ac-
tions into separate threads. (See the previous doorbell example.)
1001ICT Introduction To Programming – 2015-2 460
25.1.3 Event dispatch thread
Java programs so routinely require a separate thread for detecting input, that
one is built into the JVM: the event dispatch thread.
This is the thread that keeps a MaSH graphics program running even if
the main method and hence the main thread is finished.
It is this thread that calls the paintWindow method.
It does so when it detects user input, for instance when the user uses the
mouse to resize the window.
For programs to be responsive, paintWindow should do its job quickly,
so the event dispatch thread is free to handle more user input.
The kinds of user (or other) inputs that are detected by the event dispatch
thread are called events.
1001ICT Introduction To Programming – 2015-2 461
25.2 Event handlers
An event handler is a method that encapulates the actions that the program
should perform when a specific event occurs.
In general, an event handler:
• is defined like any other method in the program;
• is not called directly from within the program;
• is called by the event dispatch thread when the event occurs;
• usually has a standard name so that the dispatch thread can know to
call it; and
• usually has a name that starts with “on”.
1001ICT Introduction To Programming – 2015-2 462
25.3 Doorbell example
This third doorbell program uses the ENTER button on the front of the NXT
instead of a touch sensor.
The only way the nxt environment provides a program to respond to presses
on the front panel buttons is via event handlers.
// Doorbell3.mash
// Doorbell with a scrolling message,
// using events.
import nxt;
1001ICT Introduction To Programming – 2015-2 463
// Multi-line message to scroll up the screen.
String[] message = {
" Welcome ",
" ",
"NO: ",
" salespersons, ",
" hawkers, ",
" proselytizers,",
" beggars, ",
" politicians, ",
" thieves, ",
" relatives, ",
" otherwise...",
" "
};
final int LENGTH = 12;
1001ICT Introduction To Programming – 2015-2 464
The main method now only looks after scrolling the message.
It does not need to start another thread.
void main() {
int i = 0;
while(true) {
drawString(message[i], 0, LCD_LINES - 1);
sleep(1000);
scroll();
i = (i + 1) % LENGTH;
}
}
Nor does it call the event handlers that follow.
1001ICT Introduction To Programming – 2015-2 465
This is the event handler that will be called when the ENTER putton is
pressed.
It plays the tones.
void onPressEnter() {
playNote(XYLOPHONE, 880, 400);
pause(200);
playNote(XYLOPHONE, 440, 600);
}
Finally, this event handler is needed as well, to do nothing, as there is a
default hander for releasing the ENTER button that beeps. It must be over-
ridden.
void onReleaseEnter() {
}
1001ICT Introduction To Programming – 2015-2 466
25.4 Events in the graphics environment
The graphics environment also allows the definition of event handlers,
so that programs may repond to mouse clicks and key presses.
Do the same things:
• Look for rewrite methods with names that start with “on”. They are
event handlers.
• Define the method in your program. Don’t try to call it!
• Make sure you declare the method’s parameters, as they will be passed
values by the event dispatch thread to tell your program where the
mouse was clicked or what key was pressed.
• Make sure the actions performed by the handlers don’t take longer to
execute than a very small fraction of a second.
1001ICT Introduction To Programming – 2015-2 467
This example program demonstrates the use of a mouse event handler.
/*
** file: RedBox3.mash
** purpose: Puts up a window and draws
** a red box in it. The box moves
** to where the mouse is clicked.
*/
import graphics;
void main () {
setFrameSize(200, 220);
setFrameVisible(true);
animate(30);
}
1001ICT Introduction To Programming – 2015-2 468
int bx = 50, by = 50; // box coords
void paintWindow() {
setColor(255, 0, 0);
fillRect(bx, by, 100, 100);
}
void onMouseClicked(int x, int y) {
bx = x - 50;
by = y - 50;
}
1001ICT Introduction To Programming – 2015-2 469
This example program demonstrates the use of key event handlers.
/*
** file: RedBox4.mash
** purpose: Puts up a window and draws
** a red box in it. The box moves
** when the arrow keys are down.
*/
import graphics;
void main () {
setFrameSize(200, 220);
setFrameVisible(true);
animate(30);
}
1001ICT Introduction To Programming – 2015-2 470
int bx = 50, by = 50; // box coords
boolean leftDown = false, // arrow key down
rightDown = false,
upDown = false,
downDown = false;
void paintWindow() {
// draw
setColor(255, 0, 0);
fillRect(bx, by, 100, 100);
// move
if (leftDown) {
bx = bx - 1;
} else {
}
if (rightDown) {
bx = bx + 1;
1001ICT Introduction To Programming – 2015-2 471
} else {
}
if (upDown) {
by = by - 1;
} else {
}
if (downDown) {
by = by + 1;
} else {
}
}
void onKeyPressed(int code) {
if (code == 37) {
leftDown = true;
} else if (code == 38) {
upDown = true;
1001ICT Introduction To Programming – 2015-2 472
} else if (code == 39) {
rightDown = true;
} else if (code == 40) {
downDown = true;
} else {
}
}
void onKeyReleased(int code) {
if (code == 37) {
leftDown = false;
} else if (code == 38) {
upDown = false;
} else if (code == 39) {
rightDown = false;
} else if (code == 40) {
downDown = false;
1001ICT Introduction To Programming – 2015-2 473
} else {
}
}
1001ICT Introduction To Programming – 2015-2 474
25.5 Section summary
This section covered:
• events;
• the event dispatch thread; and
• event handlers.
1001ICT Introduction To Programming – 2015-2 475
25.6 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 476
26 Boolean Algebra
Every program with selections or loops, uses Boolean values, computed
with Boolean expressions, in the conditions.
It is an advantage for programmers to be able to simplify their conditions to
make them clearer.
The power of symbolic logic is realised when we learn to simplify formulas
containing relational and Boolean operators.
Your maths course will be a more complete introduction to Boolean algebra,
but for now it is enough to learn how to simplify formulas containing nots.
1001ICT Introduction To Programming – 2015-2 477
26.1 Revision: Boolean operators
operator means examples¬ not ¬T, ¬p, ¬(x < 10)∧ and T ∧ F, p ∧ q, x < 10 ∧ y = 0∨ or T ∨ F, p ∨ q, x < 10 ∨ y = 0
xor exclusive or TxorF, pxor q, x < 10xor y = 0
1001ICT Introduction To Programming – 2015-2 478
26.2 Double negation
¬(¬p) = p
1001ICT Introduction To Programming – 2015-2 479
26.2.1 Negating relational operators
¬(x < y) = x ≥ y
¬(x ≤ y) = x > y
¬(x = y) = x ≠ y
¬(x > y) = x ≤ y
¬(x ≥ y) = x < y
¬(x ≠ y) = x = y
1001ICT Introduction To Programming – 2015-2 480
26.2.2 Negating ands and ors (DeMorgan’s theorems)
If you have two conditions p and q, then DeMorgan’s theorems show how
to negate their combinations using and (∧) or or (∨).
¬(p ∧ q) = ¬p ∨ ¬q¬(p ∨ q) = ¬p ∧ ¬q
If you have more than two conditions:
¬(p ∧ q ∧ r ∧ . . .) = ¬p ∨ ¬q ∨ ¬r ∨ . . .¬(p ∨ q ∨ r ∨ . . .) = ¬p ∧ ¬q ∧ ¬r ∧ . . .
1001ICT Introduction To Programming – 2015-2 481
26.2.3 Example
Recall this laboratory exercise:
Write a program that drives the robot forward on the track. The
robot should stop when either the robot runs into an obstacle
(the bollard) or drives on to the dark area.
The solution is to write a while loop to wait until either of the reasons to
stop is true.
Writing the right loop condition is tricky because the question is written in
terms of the reasons to stop, whereas the loop condition must be written in
terms of reasons to continue.
Fortunately one is just the negation of the other.
1001ICT Introduction To Programming – 2015-2 482
Reason to stop: touch sensor pushed or light sensor value low.
isPushed(TOU) || getLight(LIG) < 45
The loop condition should be the negation of that:
while (!(isPushed(TOU) || getLight(LIG) < 45)) {
}
Use DeMorgan’s theorem to distribute ! and change || to &&:
while (!isPushed(TOU) && !(getLight(LIG) < 45)) {
}
Simplify the light part:
while (!isPushed(TOU) && getLight(LIG) >= 45) {
}
1001ICT Introduction To Programming – 2015-2 483
26.3 Section summary
This section covered:
• a little algebra that’s useful to programmers (negating).
1001ICT Introduction To Programming – 2015-2 484
26.4 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 485
27 Searching
Many programs require a search for a particular value in some sequential
data structure (e.g. an array or a String).
In this section we will explore some important searching algorithms.
27.1 A problem requiring searching
For example, suppose we want to write a program that counts the number
of distinct words in a text.
To do that, each word must be compared with all of the words encountered
so far to see if it is a new one to be counted.
We will write programs to do this. Along the way we will have to solve
some ancillary problems and will be able to reuse methods from previous
lecture examples.
1001ICT Introduction To Programming – 2015-2 486
27.2 Version 1 – Linear search
Start with the identifying comment and choose the right MaSH environ-
ment.
/*
** file: Linear.mash
** author: Andrew Rock
** purpose: Program to count the number of distinct
** words in a text using a linear search.
*/
import console;
1001ICT Introduction To Programming – 2015-2 487
For this problem we can use an array to store the set of words already en-
countered.
We must make it big enough to hold all the distinct words we can expect.
We also need a variable to remember how many distinct words are actually
in the array.
final int MAX = 10000; // maximum distinct words
String[] word = new String[MAX]; // distinct words
int numWords = 0; // number of distinct words
1001ICT Introduction To Programming – 2015-2 488
An important question is what do we call a word for the purposes of this
program?
The readWord function in the console environment treats any sequence
of non-whitespace characters as a word, but that would include punctuation
marks.
Also, case should be ignored.
The following function removes all of the non-letters from a string and re-
turns all of the letters in upper case.
It is possible that after removing all the non-letters, there are no characters
left.
1001ICT Introduction To Programming – 2015-2 489
// lettersOnly(s) returns only the letters in
// s in upper case.
String lettersOnly(String s) {
String t = "";
for (int i = 0; i < length(s); i = i + 1) {
char c = charAt(s, i);
if (’A’ <= c && c <= ’Z’) {
t = t + c;
} else if (’a’ <= c && c <= ’z’) {
t = t + (char) (c - ’a’ + ’A’);
} else {
}
}
return t;
}
1001ICT Introduction To Programming – 2015-2 490
Here is the strategy for our program:
For each word read from standard input:
• Remove all the non-letters and convert to upper case.
• If the word is now empty, don’t use it.
• Search our set of words (in the array) for the word.
• If it’s not already in the array, add it to the array.
After all the words are read, print the number of words we added to the
array.
The key part is the searching. There are many strategies for that, we will do
the simplest first, a linear search.
1001ICT Introduction To Programming – 2015-2 491
A linear search makes no assumptions about the data in the array and just
compares every element of the array starting from the first one until it
reaches the end of the array or finds what it is looking for.
The amount of time this takes is simply proportional to the size of the array
(in Maths-speak, linearly proportional to the size of the array).
The following function uses two variables i and j to define the range of
positions that might be reported by the function.
While the range is not empty (that is i < j) the function still needs to con-
tinue searching.
There are two ways to reduce the search range...
Using this function the rest of the program implements the strategy given
above.
1001ICT Introduction To Programming – 2015-2 492
// linearSearch(s, a, n) searches array a (that has
// n elements) for string s. Returning either:
// the position where s occurs in a, or
// n if s does not occur in a.
int linearSearch(String s, String[] a, int n) {
int i = 0;
int j = n;
while (i < j) {
if (equals(a[i], s)) {
j = i;
} else {
i = i + 1;
}
}
return i;
}
1001ICT Introduction To Programming – 2015-2 493
// readDistinct() reads standard input and finds
// all of the distinct words.
void readDistinct() {
while(isNextWord()) {
String w = lettersOnly(readWord());
if (length(w) > 0) {
int p = linearSearch(w, word, numWords);
if (p == numWords) {
word[numWords] = w;
numWords = numWords + 1;
println(w); // so we can see them
} else {
}
} else {
}
}
}
1001ICT Introduction To Programming – 2015-2 494
void main() {
readDistinct();
println(numWords + " distinct words");
}
Demonstrate this program with Alice In Wonderland.
1001ICT Introduction To Programming – 2015-2 495
27.3 Version 2 – Binary search
We can make a faster program, and one that sorts the words as a side benefit,
by using a binary search. It starts the same...
/*
** file: Binary.mash
** author: Andrew Rock
** purpose: Program to count the number of distinct
** words in a text using a binary search.
*/
import console;
final int MAX = 10000; // maximum distinct words
String[] word = new String[MAX]; // distinct words
int numWords = 0; // number of distinct words
1001ICT Introduction To Programming – 2015-2 496
// lettersOnly(s) returns only the letters in
// s in upper case.
String lettersOnly(String s) {
String t = "";
for (int i = 0; i < length(s); i = i + 1) {
char c = charAt(s, i);
if (’A’ <= c && c <= ’Z’) {
t = t + c;
} else if (’a’ <= c && c <= ’z’) {
t = t + (char) (c - ’a’ + ’A’);
} else {
}
}
return t;
}
1001ICT Introduction To Programming – 2015-2 497
A binary search works faster than a linear search, because all of the elements
in the array are kept in ascending order.
We can find a word in a dictionary very quickly because they are in order.
To keep words in order we will need to compare words. We solved this
problem in a previous example, so we can reuse that code:
// compare(s, t) returns
// -1 if s < t
// 0 if s == t
// +1 if s > t
int compare(String s, String t) {
int i = 0, j = min(length(s), length(t));
1001ICT Introduction To Programming – 2015-2 498
while (i < j) {
if (charAt(s, i) < charAt(t, i)) {
return -1;
} else if (charAt(s, i) == charAt(t, i)) {
i = i + 1;
} else {
return 1;
}
}
if (length(s) < length(t)) {
return -1;
} else if (length(s) == length(t)) {
return 0;
} else {
return 1;
}
}
1001ICT Introduction To Programming – 2015-2 499
The binary search function uses a range bound by i and j as before.
It always compares the element in the middle of the range with the word we
are seeking.
Then it can reject a whole half of the search range at a time, not just one
element.
// binarySearch(s, a, n) searches array a (that has
// n elements) for string s. Returning either:
// the position where s occurs in a, or
// the position where it should be inserted.
// precondition: the elements of a are in ascending
// order.
int binarySearch(String s, String[] a, int n) {
int i = 0;
int j = n;
1001ICT Introduction To Programming – 2015-2 500
while (i < j) {
int m = (i + j) / 2;
int c = compare(s, a[m]);
if (c < 0) {
j = m;
} else if (c == 0) {
i = m;
j = m;
} else {
i = m + 1;
}
}
return i;
}
1001ICT Introduction To Programming – 2015-2 501
Once we have the position where the word should be inserted, it has to be
inserted, and this requires moving all the elements after that position along
one space.
// insert(a, n, s, i) inserts s into array a
// with n elements at position i.
void insert(String[] a, int n, String s, int i) {
for(int j = n; j > i; j = j - 1) {
a[j] = a[j-1];
}
a[i] = s;
}
The rest of the program follows the same basic strategy again. To show that
the words are sorted by this process, they will be printed.
1001ICT Introduction To Programming – 2015-2 502
// readDistinct() reads standard input and finds
// all of the distinct words.
void readDistinct() {
while(isNextWord()) {
String w = lettersOnly(readWord());
if (length(w) > 0) {
int p = binarySearch(w, word, numWords);
if (p == numWords || !equals(w, word[p])) {
insert(word, numWords, w, p);
numWords = numWords + 1;
} else {
}
} else {
}
}
}
1001ICT Introduction To Programming – 2015-2 503
// printWords() prints all the words.
void printWords() {
for (int i = 0; i < numWords; i = i + 1) {
println(word[i]);
}
}
void main() {
readDistinct();
printWords();
println(numWords + " distinct words");
}
1001ICT Introduction To Programming – 2015-2 504
27.4 Parallel arrays
So far we have only been interested in the number of distinct words.
Often we are interested in counting the number of times each distinct word
occurs, that is its frequency.
Now we need to associate a count with each word.
A solution is to have a second (parallel) array of ints, where the count for
a word is maintained in the same relative position.
A solution to this problem will be (time permitting) developed in a work-
shop, starting from Linear.mash and adapting it to this new task.
1001ICT Introduction To Programming – 2015-2 505
27.5 Section summary
This section covered:
• a linear search example;
• a binary search example; and
• the idea of parallel arrays.
1001ICT Introduction To Programming – 2015-2 506
27.6 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 507
28 Why MaSH Is Rubbish
In this final section, we:
• review the concepts that we have learned about programming using
the Java subset language, MaSH;
• identify the essential omissions from MaSH that make it impossible
to use for all but very small programs; and
• preview the Java language features that solve these problems.
1001ICT Introduction To Programming – 2015-2 508
28.1 Basic programming concepts in review
Here is a list of concepts and questions about them that have been covered
in this course.
They are all concepts that will be assumed knowledge in Object Oriented
Programming.
As a class, verbally define each concept, and answer the questions?
• text file
• binary file
• programming language
• high-level programming language
– What are the 5 generations of programming languages?
1001ICT Introduction To Programming – 2015-2 509
• source file
• .class file
• syntax
• semantics
• lexical syntax
• context-free grammar
• whitespace
• newline
• comment
1001ICT Introduction To Programming – 2015-2 510
• keyword
– List 10 Java keywords you have used.
• literal
– How do you tell a String literal from a char literal?
• operator
– List 10 Java operators you have used.
– List the 10 operators in order of precedence.
• type
– List 5 Java types you have used.
• variable declaration
1001ICT Introduction To Programming – 2015-2 511
• assignment statement
• procedure call
• initialisation
• structured statement
• definite loop
– What is the Java statement used to make a definite loop?
• indefinite loop
– What are the Java statements used to make indefinite loops?
– how do they differ?
1001ICT Introduction To Programming – 2015-2 512
• selection
– What is the Java statement used to make a selection?
• method
• procedure
– What keyword indicates that a method is a procedure?
• function
– What is the important difference between a function and a pro-
cedure?
• formal parameter list
• actual parameter list
1001ICT Introduction To Programming – 2015-2 513
• global variable
• local variable
• scope
• lifetime
– Which have the longer lifetimes, local or global variables?
• array
• parallel arrays
• API
• reuse
• cohesion
1001ICT Introduction To Programming – 2015-2 514
How did you go?
If you could not define/answer the majority of these, you will have to catch
up this material before Object Oriented Programming.
Before you start Object Oriented Programming, review this list again.
1001ICT Introduction To Programming – 2015-2 515
28.2 Important problems that need solving
MaSH is rubbish because:
• The APIs, the environments, are fixed and too restrictive.
• The environments can’t be extended in the MaSH language itself.
• You can only import one environment at a time.
• A MaSH program has to be all in one file.
• To reuse a method from one MaSH program to the next, it has to be
copied. Now it’s in two places, and hard to maintain.
• You can not split a program into pieces so that different people can
work on each part separately.
• You can not define new data types.
1001ICT Introduction To Programming – 2015-2 516
28.3 Java language features
28.3.1 Classes and objects
To solve all of the above problems, the Java language organises code into
classes.
Each class is usually defined in a separate .java file.
So:
• different people can work on parts of a program; and
• code can be written once in a class and reused by multiple programs.
A class creates a new data type.
Actual instances of these new data types, are object.
1001ICT Introduction To Programming – 2015-2 517
28.3.2 Public versus private
Good fences make good neighbours.
Programmers work well together when they can control how other program-
mers’ code will interact with their own.
The variables and methods in a class can be marked public or private
to control their visibility (scope) from other classes.
A collection of classes is called a package.
Classes can also be marked as public or private to control their visi-
bility from other packages.
1001ICT Introduction To Programming – 2015-2 518
28.3.3 Static versus dynamic
Things that are created at run-time in a program are called dynamic.
Things that are defined/created at the time the program is written or com-
piled are called static.
All objects in a program are created at run-time, and are therefore dynamic.
Classes are static.
Objects are created, using only the dynamic definitions in a class.
By default, the things you define in a class (variables, methods...) are dy-
namic, but the keyword static marks something as static, and belonging
to the class.
1001ICT Introduction To Programming – 2015-2 519
28.3.4 Qualification
To refer to a variable or method in another class or object, its name must be
qualified with the name of the class or object it belongs to.
Examples:
• someObject.someVariable = 3;
• SomeClass.someProcedure();
• System.out.println("Hello, World!");
println is a method that belongs to an object called out, which belongs
to class System.
Note how the case of the first letter of a name tells the difference between a
class and an object.
1001ICT Introduction To Programming – 2015-2 520
28.3.5 Hello again, and goodbye
At last, we know enough to read everything in the first program that ap-
peared in this course.
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
This concludes Introduction To Programming. All the best for Object Ori-
ented Programming.
1001ICT Introduction To Programming – 2015-2 521
28.4 Section summary
This section covered:
• a review of programming concepts;
• what things MaSH can’t do; and
• how Java does those things.
1001ICT Introduction To Programming – 2015-2 522
28.5 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 523
A Conventions Used In these Notes
This appendix explains the typographic conventions used in these lecture
notes, laboratory exercises, etc.
1001ICT Introduction To Programming – 2015-2 524
A.1 Typefaces
Proportionally spaced, serif typeface is used for the body (English) text
of these notes.
Example: Study hard.
Equally (mono-)spaced, serif typeface is used to show plain text as it would
appear in a program (in any programming language) or for textual in-
puts or outputs from programs.
Example: println("Study hard.");
Sans-serif typeface is used for naming applications, menu items and other
elements in graphical user interfaces.
Example: File ▶ Save As...
1001ICT Introduction To Programming – 2015-2 525
A.2 Program code
Program code (whole programs or snippets) is displayed in mono-spaced
typeface without any further adornment.
Example:
import console;
println("Programming should be fun!");
1001ICT Introduction To Programming – 2015-2 526
A.3 Program code templates
Sometimes a code snippet is generalised, with some text not to be copied
literally, but to be replaced with other text.
The text to be replaced is italicised.
Example:
initialisation statement(s)
while (condition) {
body statement(s)
}
1001ICT Introduction To Programming – 2015-2 527
A.4 Console sessions
The console could be the Command Prompt in Windows, or the Terminal
in Mac OS X or Linux.
To distinguish console sessions from program code, an outline is used.
Example:
$ java Adder
Enter two numbers: 3 4
Sum = 7
$
Input, including commands, typed by the user is underlined.
1001ICT Introduction To Programming – 2015-2 528
The command prompt (for example, C:\> on Windows) that these pro-
grams display, varies from system to system, and as the current working
directory is changed. It is always represented by a shortened version.
For Windows-only examples, > is used.
For Mac OS X and Linux examples, ] is used.
When the example works on any system, $ is used.
As in program code templates, italics are used to show generic command
examples, where the italicised text should be substituted for, say, a specific
file name.
1001ICT Introduction To Programming – 2015-2 529
A.5 Section summary
This section covered:
• how code and code templates are displayed; and
• how console examples are displayed in these lecture notes.
1001ICT Introduction To Programming – 2015-2 530
A.6 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 531
B Windows Command Prompt Tutorial
The Windows Command Prompt is used in this course to compile and
run MaSH and Java programs.
This is a tutorial on its basics and some conveniences.
1001ICT Introduction To Programming – 2015-2 532
B.1 Opening the Windows Command Prompt
Go toStart▶ Programs▶ Accessories▶Windows Command Prompt.
A window appears with some text in the top left corner, this is the command
prompt.
The prompt may look like the following:
C:\>
The C:\ indicates the current drive, C:, and the current directory, \ (the
top-most or root directory).
The > is always present as decoration, and does not actually mean anything.
1001ICT Introduction To Programming – 2015-2 533
B.2 Listing directory contents – dir
Listing the directory’s contents is useful to confirm you are in the right
directory, to check whether the file you are after is in the directory, and to
check the exact spelling of a filename.
To list the contents of the current directory type dir at the command prompt
and press enter.
A listing of the current directory’s contents will appear. If the command
prompt says C:\, then you will get a listing of all of the files in the C:\ di-
rectory. If the command prompt says something like H:\ or Z:\ (i.e. your
home directory) then you will get a listing of the files in those directories.
1001ICT Introduction To Programming – 2015-2 534
This shows a typical Command Prompt window. The colours have been
added to the text.
1001ICT Introduction To Programming – 2015-2 535
B.3 Changing drives
If your files are on a different drive to the one displayed in the command
prompt then you will need to change to that drive.
For example, if the prompt says C:\ but your files are on your home direc-
tory (H: in Nathan and Logan, Z: on the Gold Coast) then you will need to
change to that drive first.
To change the drive type in the letter of the drive followed by a colon and
then enter. For example, to change to H: simply type H: then enter.
C:\> H:
H:\>
Once you have changed drives list the directory contents to ensure you are
on the correct drive.
1001ICT Introduction To Programming – 2015-2 536
B.4 Changing directories – cd
You should have directories in your home drive which you have created to
organise the files for the different courses you are enrolled in.
You will need to change to one of those directories to be able to access the
files in those directories.
If you don’t have any directories on your home drive then create one for
1001ICT using Windows Explorer.
The Windows command for changing directories is cd followed by the
name of the directory to change into.
For example if your Introduction To Programming files are in a directory
called 1001ict then to change into that directory you would need to type
cd 1001ict and press enter.
1001ICT Introduction To Programming – 2015-2 537
H:\> cd 1001ict
H:\1001ict\>
The prompt would is changed to indicate that you are in the 1001ict
directory.
You may need to change directories again. For example, in your 1001ict
directory you may have a directory for MaSH programs. If so, change di-
rectories again by typing cd followed by the name of the directory, e.g.
cd MaSH.
1001ICT Introduction To Programming – 2015-2 538
B.5 Command history
Typing commands can become laborious when we repeat the same sequence
of commands over and over again.
For example we may compile a file, run it, find a bug, and compile and run
it again.
The Windows Command Prompt stores a history of the commands we
have entered to save us retyping them.
We scroll through the history by using the up and down arrow keys. The up
arrow key moves backwards through the history.
1001ICT Introduction To Programming – 2015-2 539
For example, if I typed the following three lines:
H:\1001ict\MaSH\> mashc HelloWorld.mash
H:\1001ict\MaSH\> javac HelloWorld.java
H:\1001ict\MaSH\> java HelloWorld
Hello World
H:\1001ict\MaSH\>
Pressing the up arrow would display java HelloWorld at the command
prompt and pressing the up arrow again would replace it with the previous
command javac HelloWorld.java, etc.
1001ICT Introduction To Programming – 2015-2 540
B.6 File name completion
To further ease the tedium of typing commands, we have the file name com-
pletion feature.
Type a command, but don’t finish typing the whole file name:
H:\1001ict\MaSH\> javac Hel
Then press the tab key. The rest of the file name will be typed for you.
If it is the wrong file name, e.g. HelloWorld.class instead of
HelloWorld.java, then keep pressing the tab key until you get the
name that you want.
1001ICT Introduction To Programming – 2015-2 541
B.7 Dragging files and folders
Getting to the right folder using cd can also be tedious.
A shortcut is to drag the icon for a file or folder from the Windows Explorer
onto the Command Prompt window.
The full path of the file or folder will be typed onto the command line for
you.
1001ICT Introduction To Programming – 2015-2 542
B.8 Section summary
This section covered:
• opening the Windows Command Prompt;
• listing directory contents;
• changing drive;
• changing directory;
• command history; and other shortcuts.
1001ICT Introduction To Programming – 2015-2 543
B.9 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 544
C Mac OS X Terminal Tutorial
The Mac OS X Terminal is used in this course to compile and run MaSH
and Java programs.
This is a tutorial on its basics and some conveniences.
Aside from the details which are Mac-specific, like how to run the Termi-
nal, much of what follows applies to Linux, as it uses the same shell, bash.
1001ICT Introduction To Programming – 2015-2 545
C.1 Opening the Terminal
The Terminal is a utility, stored in the usual place:
/Applications/Utilities/.
Open it, and a window appears with some text in the top left corner, this
is a virtual terminal. (A physical terminal used to be a very low powered
computer that could only display text sent from a remote host.)
The prompt can vary depending on how your system is set up, but it is
usually a string that shows some or all of: which computer you are using;
your login name; which directory is the current working directory.
1001ICT Introduction To Programming – 2015-2 546
For example:
Andrew-Rocks-Mac-Pro:˜ arock$
The computer is Andrew-Rocks-Mac-Pro. User arock is logged in.
The current working directory is ˜, which is Unix shorthand for the user’s
home directory. The dollar sign is always present, and does not actually
mean anything. In examples we often just display the prompt as $ by itself.
Note that the Terminal utility is a Mac application that provides the text
display in a window.
The program that is prompting for input is the shell. There are several
choices for shells in Unix and the default in Mac OS X, bash, is usually
the default in Linux too.
1001ICT Introduction To Programming – 2015-2 547
C.2 Listing directory contents – ls
Listing the directory’s contents is useful to confirm you are in the right
directory, to check whether the file you are after is in the directory, and to
check the exact spelling of a filename.
To list the contents of the current directory type ls at the command prompt
and press enter.
A listing of the current directory’s contents will appear. If the command
prompt says ˜ then you will get a listing of all of the files in your home
directory.
1001ICT Introduction To Programming – 2015-2 548
This shows a typical Terminal window. The colours have been added to the
text.
1001ICT Introduction To Programming – 2015-2 549
C.3 Changing directories – cd
It is good practice to make a separate folder (also known as a directory)
for each piece of work you produce, particularly programs as they typically
consist of many files that should be kept grouped. To work on files in the
terminal, it is best to make the folder with your current work the current
working directory.
The Unix command for changing directories is cd followed by the name of
the directory to change into.
For example if your Introduction To Programming files are in a directory
called 1001ict then to change into that directory you would need to type
cd 1001ict and press return.
1001ICT Introduction To Programming – 2015-2 550
$ cd 1001ict
$
The full prompt will change to indicate that you are in the 1001ict direc-
tory.
You may need to change directories again. For example, in your 1001ict
directory you may have a directory for MaSH programs. If so, change di-
rectories again by typing cd followed by the name of the directory, e.g.
cd MaSH.
1001ICT Introduction To Programming – 2015-2 551
C.4 Command history
Typing commands can become laborious when we repeat the same sequence
of commands over and over again.
For example we may compile a file, run it, find a bug, and compile and run
it again.
The shell stores a history of the commands we have entered to save us re-
typing them.
We scroll through the history by using the up and down arrow keys. The up
arrow key moves backwards through the history.
1001ICT Introduction To Programming – 2015-2 552
For example, if I typed the following three lines:
$ mashc HelloWorld.mash
$ javac HelloWorld.java
$ java HelloWorld
Hello World
$
Pressing the up arrow would display java HelloWorld at the command
prompt and pressing the up arrow again would replace it with the previous
command javac HelloWorld.java, etc.
1001ICT Introduction To Programming – 2015-2 553
C.5 File name completion
To further ease the tedium of typing commands, we have the file name com-
pletion feature.
Type a command, but don’t finish typing the whole file name:
$ javac Hel
Then press the tab key. The rest of the file name will be typed for you.
If there are more than one file that start the same way, the shell will add as
many characters as it can, beep and wait for you to type some more to help
it work out which file you want. Press tab again to get the shell to complete
the name.
1001ICT Introduction To Programming – 2015-2 554
C.6 Dragging files and folders
Getting to the right folder using cd can also be tedious.
A shortcut is to drag the icon for a file or folder from the Finder onto the
Terminal window.
The full path of the file or folder will be typed onto the command line for
you.
1001ICT Introduction To Programming – 2015-2 555
C.7 Other disks
If your work is on another disk (or volume, as they are known to Mac OS
X), what to type after cd can be difficult to figure out.
The best way to cd to a folder on another volume is using the dragging
method.
When you do so you will discover that your other disks appear as if they
were folders inside the invisible directory called /Volumes/.
1001ICT Introduction To Programming – 2015-2 556
C.8 Section summary
This section covered:
• opening the Terminal;
• listing directory contents;
• changing directory;
• command history; and other shortcuts.
1001ICT Introduction To Programming – 2015-2 557
C.9 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 558
D Installing the JDK
This appendix describes how to obtain and install the Java development kit
(JDK) standard edition (SE), on your own computer (Windows, Mac OS X,
or Linux).
1001ICT Introduction To Programming – 2015-2 559
D.1 JDK versus JRE
You most likely already have Java installed on your computer, in the form
of the Java runtime environment (JRE).
This contains all of the resources required to run Java software, but not to
compile it.
The JRE contains the Java virtual machine, java, but not the Java com-
piler, javac, which is only included in the JDK.
1001ICT Introduction To Programming – 2015-2 560
D.2 For Windows
Obtain the JDK from Oracle web site:
www.oracle.com/technetwork/java/javase/downloads/
Get the latest version that appears to match your system.
If you have problems with the 64 bit version, download the 32 bit version
instead.
The download is a self extracting installer. Just install like any application,
leaving all of the settings at their defaults.
1001ICT Introduction To Programming – 2015-2 561
D.2.1 Setting the path
The installer does everything required to use the JDK, except make javac
and the other bundled tools available for use in the Command Prompt.
The Command Prompt needs to be told where the tools are.
This is done by modifying the path system environment variable so that it
includes the path to the folder that contains javac.exe.
1001ICT Introduction To Programming – 2015-2 562
Use the Windows Explorer to locate where the JDK has been installed in
the Program Files folder.
Locate the bin folder that contains javac.exe.
Copy the full path of that folder.
Open up the system control panel.
Look for the advanced system setting, and the button, Environment Vari-
ables.
That opens a dialogue box where the variables may be edited.
At the top are the user variables that you should modify, and at the bottom
are system-wide variables that you should not modify.
1001ICT Introduction To Programming – 2015-2 563
If there is no pre-existing user Path variable, create one, and set its value
to the path to the bin folder you copied.
If one already exists, edit it, and add the copied path to the end of the ex-
isting value. Use a semicolon to separate the new path from the preceding
one.
Close the control panels, and make a new Command Prompt window.
Type javac to confirm that it runs.
1001ICT Introduction To Programming – 2015-2 564
D.3 For Mac OS X
The only source for an up-to-date Java is now Oracle.
Apple used to make its own port of Java to Mac OS X, but it has stopped
doing this. This is a good thing, as the Apple version was always a bit
behind the others.
Download the latest JDK SE for Mac OS X from the same source as for
Windows, and install like any other app.
That’s it.
1001ICT Introduction To Programming – 2015-2 565
D.4 For Linux
The best source for Linux, is via the package manager for your distro.
1001ICT Introduction To Programming – 2015-2 566
D.5 Section summary
This section covered:
• how to obtain the Java software used in this course and install it on
your own computer.
1001ICT Introduction To Programming – 2015-2 567
D.6 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 568
E Installing MaSH
This appendix describes how to obtain and install the Making Stuff Happen
system on your own computer (Windows, Mac OS X, or Linux).
1001ICT Introduction To Programming – 2015-2 569
E.1 For all systems
Obtain the MaSH from the MaSH home page:
www.ict.griffith.edu.au/arock/MaSH/
Scroll down to the Downloads section, and look for MaSH Binaries.
Download the most recent zip file that most closely matches your system.
Unpack the zip file and rename the resulting folder to just mash.
Now go to the section below for your system.
1001ICT Introduction To Programming – 2015-2 570
E.2 For Windows
E.2.1 Move the folder into place
Move the mash folder to somewhere convenient.
Suggestions: In the Program Files folder, right next to the Java folder;
or in your user home folder.
1001ICT Introduction To Programming – 2015-2 571
E.2.2 Setting the path
The Command Prompt needs to be told where the MaSH tools are.
This is done by modifying the path system environment variable so that it
includes the path to the folder that contains mashc.exe.
1001ICT Introduction To Programming – 2015-2 572
Use the Windows Explorer to locate the mash folder.
Inside that, locate the bin folder that contains mashc.exe.
Copy the full path of that folder.
Open up the system control panel.
Look for the advanced system setting, and the button, Environment Vari-
ables.
That opens a dialogue box where the variables may be edited.
At the top are the user variables that you should modify, and at the bottom
are system-wide variables that you should not modify.
1001ICT Introduction To Programming – 2015-2 573
If there is no pre-existing user Path variable, create one, and set its value
to the path to the bin folder you copied.
If one already exists, edit it, and add the copied path to the end of the ex-
isting value. Use a semicolon to separate the new path from the preceding
one.
Close the control panels, and make a new Command Prompt window.
Type mashc to confirm that it runs.
1001ICT Introduction To Programming – 2015-2 574
E.2.3 Setting the environment path
The MaSH compiler, mashc.exe, needs to be told where the MaSH envi-
ronments are.
This is done by modifying the system environment variable MASH_ENV_PATH
so that it includes the path to the folder that contains console.mashenv.
1001ICT Introduction To Programming – 2015-2 575
Use the Windows Explorer to locate where the mash folder.
Inside that, locate the env folder that contains console.mashenv.
Copy the full path of that folder.
Open up the system control panel.
Look for the advanced system setting, and the button, Environment Vari-
ables.
That opens a dialogue box where the variables may be edited.
Add a new user variable (in the top section) called MASH_ENV_PATH, and
set the value to the the copied path.
1001ICT Introduction To Programming – 2015-2 576
E.3 For Mac OS X and Linux
This assumes that you are using the default shell, bash. If you have
changed that, you are an advanced user, and you’re on your own.
Move the mash folder to somewhere convenient.
Suggestion: in your user home folder, which has the convenient path abbre-
viation, ˜.
If you choose somewhere else, make appropriate adjustments to the com-
mands below.
1001ICT Introduction To Programming – 2015-2 577
E.3.1 Setting the path and the environment path
bash needs to be told where the MaSH tools are and mashc needs to know
where the environment files are.
This is done by adding commands to the file ˜/.bash_profile.
Any file that starts with . is normally hidden.
Use these commands in a terminal to see the hidden files in your home
folder:
] cd
] ls -a
1001ICT Introduction To Programming – 2015-2 578
Open (or create) the file ˜/.bash_profile with the editor pico:
] pico .bash_profile
Enter these commands carefully:
# MaSH setups
PATH=$PATH:˜/mash/bin
export MASH_ENV_PATH=˜/mash/env
Exit and save the file.
Make a new terminal.
Check that no error messages are produced by the commands in
˜/.bash_profile, and that mashc runs.
1001ICT Introduction To Programming – 2015-2 579
E.4 Section summary
This section covered:
• how to obtain the MaSH software used in this course and install it on
your own computer.
1001ICT Introduction To Programming – 2015-2 580
E.5 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 581
F Character Sets
Programs are created using programming languages.
Programs are nearly always created using a very limited set of characters,
the characters in the American Standard Code for Information Interchange
(ASCII) character set.
This section descibes the ASCII set and its superset, Unicode.
1001ICT Introduction To Programming – 2015-2 582
F.1 ASCII
The American Standard Code for Information Interchange was first used
for telex communications (the successor to telegraphs), and so predates its
use in computers.
It uses 7 bits (binary digits, 1s or 0s) to represent the numbers from 0 to
127.
Each number value represents a letter, a digit, a punctuation mark, whites-
pace, or control characters.
1001ICT Introduction To Programming – 2015-2 583
F.1.1 The whole ASCII set
+ 0 1 2 3 4 5 6 7 8 9
0 NUL SOH STX ETX EOT ENQ ACK BEL BS HT
10 LF VT FF CR SO SI DLE DC1 DC2 DC3
20 DC4 NAK SYN ETB CAN EM SUB ESC FS GS
30 RS US SP ! " # $ % & ’
40 ( ) * + , - . / 0 1
50 2 3 4 5 6 7 8 9 : ;
60 < = > ? @ A B C D E
70 F G H I J K L M N O
80 P Q R S T U V W X Y
90 Z [ \ ] ˆ _ ‘ a b c
100 d e f g h i j k l m
110 n o p q r s t u v w
120 x y z { | } ˜ DEL
1001ICT Introduction To Programming – 2015-2 584
F.1.2 Useful non-printing characters
value name keyboard description
0 NUL Used to represent the end of a stream of
text, particularly in the C language.
3 ETX control-C Can be used to kill programs from the con-
sole on most operating systems.
4 EOT control-D Simulate the end-of-file on unix-like sys-
tems.
7 BEL control-G Rings a bell or beeps.
8 BS control-H,
backspace
Delete left.
26 SUB control-Z Simulate the end-of-file on Windows.
27 ESC esc Escape.
127 DEL delete Delete right.
1001ICT Introduction To Programming – 2015-2 585
F.1.3 Printing characters
Letters and digits:
values glyphs description
48 to 57 0 to 9 decimal digits
65 to 90 A to Z upper case letters
97 to 122 a to z lower case letters
Parentheses, braces and brackets. Learn the difference!
values glyphs description
40, 41 (, ) left, right parentheses
60, 62 <, > less than, greater than signs, or left, right
angle brackets
91, 93 [, ] left, right (square) brackets
123, 125 {, } left, right braces
1001ICT Introduction To Programming – 2015-2 586
Punctuation marks and special symbols. Learn all their names!
value glyph description
33 ! exclamation mark, bang
34 " double quote
35 # number sign, hash, octothorpe, or pound
sign, but only if you’re American
36 $ dollar sign
37 % percent sign
38 & ampersand, “and” sign
39 ’ apostrophe, or right single quote
42 * asterisk
43 + plus sign
44 , comma
45 - hyphen, or minus sign
46 . period, full stop, or decimal point
47 / (forward) slash
1001ICT Introduction To Programming – 2015-2 587
value glyph description
58 : colon
59 ; semicolon
61 = equals sign
63 ? question mark
64 @ “at” sign
92 \ backslash
94 ˆ caret, circumflex
95 _ underscore
96 ‘ grave accent, left single quote
124 | vertical bar, pipe
126 ˜ tilde
1001ICT Introduction To Programming – 2015-2 588
Useful whitespace characters:
value name keyboard description
9 HT control-I
tab
tabulate, expands to between 1 and 8
spaces
10 LF control-J line feed, the newline character for
unix-like systems
12 FF control-L form feed, advances to the next page
13 CR control-M
return (Mac)
enter (Windows)
carriage return, the newline character
for some systems including pre-OS X
Macs
32 SP space bar the ordinary space character
Newline is used to get to the next line, and is system dependent.
Newline on Windows is a CR LF sequence.
1001ICT Introduction To Programming – 2015-2 589
F.2 Unicode
To accommodate languages other than English, mathematics and other needs,
the ASCII set is being extended with Unicode.
Programmers are having to cope with character data in Unicode, but for
convenience of typing, are still creating programs in just the ASCII set.
1001ICT Introduction To Programming – 2015-2 590
F.3 Section summary
This section covered:
• the ASCII set; and
• introduced Unicode.
1001ICT Introduction To Programming – 2015-2 591
F.4 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 592
G File Types
As we program, we will be saving our work in various types of files.
This section describes various kinds of files you will encounter this semester.
1001ICT Introduction To Programming – 2015-2 593
G.1 Filename extensions
A very old convention for identifying the type of information in a file is the
filename extension.
The extension is the few letters after the period (.). You already know a lot
of these. What are these?
.txt .wav .bmp .jpg .jpeg
.aiff .ps .pdf .doc .mov
.html .htm .zip .tiff .ai
Note that some are just 3-letter versions of a longer one, for older systems
that limit extensions to 3 letters. People who only use computers really
don’t need to see these extensions, and so the system hides them.
Programmers use unusual (and often define their own) extensions, so they
need to see them. Turn that option on on your machine!
1001ICT Introduction To Programming – 2015-2 594
G.2 Text files versus binary files
All files on a computer contain information encoded in binary, a sequence
of 1s and 0s.
Even so, we usually categorize files as either plain text files or binary files
files.
Text files consist only of a sequence of binary codes, each representing 1
character (an ASCII or Unicode value).
A binary file is a file containing anything else.
1001ICT Introduction To Programming – 2015-2 595
G.2.1 Text files
Text files are human-readable (when displayed with very simple software)
and machine-readable (by programs).
Text files can be unstructured, for human-to-human communication, or struc-
tured so that it can be read by a computer program.
Example structured text file formats:
.ps .pdf .html .xml .bat
Most programming languages are structured text files.
Conversely many files we think of as data files are actually programs, eg
PostScript and Portable Document Format (PDF).
Text files can be edited by many programs.
The text file editor is the most basic tool programmers use.
1001ICT Introduction To Programming – 2015-2 596
G.2.2 Binary files
Binary files are created and used by programs.
Their formats are defined by those programs and can not be edited manually.
Example binary formats:
.exe .bmp .jpg .jpeg .doc
.aiff .mov .zip .tiff .psd
Notice the inclusion of .doc in that list.
Word files are binary files with text embedded in them. The formatting
information is encoded in binary.
Don’t try to use Word as a program editor.
1001ICT Introduction To Programming – 2015-2 597
G.2.3 Mixed format files
Text files can contain binary data.
Eg an Extensible Markup Language (XML) file may be used to wrap binary
data.
Binary files can contain text.
Eg Word, or a JPEG photo that contains textual metadata describing the
camera and its settings that captured it.
1001ICT Introduction To Programming – 2015-2 598
G.3 Important file types
G.3.1 Windows executable binaries
Extension: .exe
Type: binary
Most programs on Windows are compiled to Intel machine code.
As a consequence, that is the only platform on which they can run.
1001ICT Introduction To Programming – 2015-2 599
G.3.2 Java source files
Extension: .java
Type: text
These files are created by Java programmers and are read by the Java com-
piler. They are the source from the Java compiler’s point of view.
1001ICT Introduction To Programming – 2015-2 600
G.3.3 Java class files
Extension: .class
Type: binary
The output from the Java compiler.
The exact format is Java bytecode.
A complete program might consist of many .class files.
Bytecode is like machine code, but can be run with an interpreter on many
platforms. Eg Java compiled on Windows can run on a Mac or an NXT.
1001ICT Introduction To Programming – 2015-2 601
G.3.4 Java archive files
Extension: .jar
Type: binary
A .jar file is like a .zip file. It is used to collect up all the .class files
that make up a program in one file.
Most Java programs are deployed as .jar files.
1001ICT Introduction To Programming – 2015-2 602
G.3.5 MaSH source files
Extension: .mash
Type: text
The programming language source file you will be creating.
1001ICT Introduction To Programming – 2015-2 603
G.3.6 Lejos NXJ binary files
Extension: .nxj
Type: binary
A .nxj file is a file that collects up all the .class files that make up a
program and is downloaded to the NXT robotics platform.
1001ICT Introduction To Programming – 2015-2 604
G.4 Section summary
This section covered:
• file extensions;
• text versus binary file formats; and
• important file types for Java programing.
1001ICT Introduction To Programming – 2015-2 605
G.5 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 606
H Syntax Diagram Notation
This appendix summarises the syntax diagram notation.
1001ICT Introduction To Programming – 2015-2 607
To describe, formally, the syntax of a programming language we will use is
the syntax or railroad diagram.
If you can appreciate that a train on a train track can not make sharp turns,
then you can read these diagrams.
Start at the left. Any path you take that gets to the right end will produce a
syntactically correct text.
1001ICT Introduction To Programming – 2015-2 608
As you traverse the path, you meet text in boxes, the elements:
• Text that appears in a round-cornered (green-filled) rectangle appears
as-is (literally) in the program.
• Text that appears in a rectangle (orange-filled) represents a syntactic
element that is defined in another syntax diagram, the one with that
name at its top-left.
• Italicised text in a rectangle (yellow-filled) is an informal description.
The path can be red or black:
• A black path indicates that there can be whitespace between the ele-
ments.
• A red path indicates that there can be no whitespace between the ele-
ments. This is used exclusively for lexical syntax.
1001ICT Introduction To Programming – 2015-2 609
H.1 Section summary
This section covered:
• the basic rules of syntax diagrams.
1001ICT Introduction To Programming – 2015-2 610
H.2 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 611
I The Statements Level Language
I.1 Introduction
This document defines the MaSH programming language at its statements
level.
The statements level omits all control structures.
It permits focus on declaring and using variables and constants, and using
the APIs provided by MaSH environments.
1001ICT Introduction To Programming – 2015-2 612
I.2 Lexical syntax
The MaSH lexical syntax describes how to make up the tokens that make
up the MaSH language out of individual characters.
We can describe a syntax either informally in plain language, or formally
with special languages like Extended Bachus-Naur Form (EBNF) or equiv-
alent diagrammatic representations such as railroad diagrams.
This document uses English and railroad diagrams.
1001ICT Introduction To Programming – 2015-2 613
I.2.1 Kinds of characters
Certain kinds of characters are appropriate in different places in a MaSH
program.
Letters
A letter is an upper or lower case letter from the
modern Latin alphabet.
letter
a
...
z
A
...
Z
1001ICT Introduction To Programming – 2015-2 614
Digits
Ordinary digits are the decimal digits from 0 to 9.
digit
0
...
9
Octal digits are those we use when writing a number in octal (base 8): 0 to
7.
octalDigit
0
...
7
1001ICT Introduction To Programming – 2015-2 615
Hexadecimal digits are those we use when writing a number in hexadecimal
(base 16): 0 to 9 and the letters A to F in upper or lower case.
hexDigit
0
...
9
a
...
f
A
...
F
1001ICT Introduction To Programming – 2015-2 616
Whitespace characters
Whitespace characters are those characters that exist in a text file, but don’t
normally show up as a visible glyph when the file is viewed, and cause the
visible characters to be spaced out either horizontally or vertically.
Common whitespace characters include the ordinary space (you put be-
tween words when you press the spacebar on your keyboard), the tab char-
acter used for aligning text, the newline character that marks the end of each
line, and some much more rarely used others.
whitespace
space
tab
newline
...
1001ICT Introduction To Programming – 2015-2 617
In a program, the whitespace is really only significant if it separates two
tokens (e.g. identifiersindexidentifier) that could otherwise be taken as one
token if there were not whitespace characters between them.
However, the use of whitespace is important to improve the readability of a
program for humans.
1001ICT Introduction To Programming – 2015-2 618
I.2.2 Comments
Comments are text for human readers only and are treated like whitespace
by compilers.
Java and MaSH have the same syntax as C++. One kind is the same as those
used in the C language.
comment
cComment
eolComment
1001ICT Introduction To Programming – 2015-2 619
C-style comments
A C-style comment may extend over may lines of text. It starts with the
characters /* and ends with */. There can be any amount of any characters
other than the sequence */ in between.
cComment
*/any characters
*/
not
/*
1001ICT Introduction To Programming – 2015-2 620
C++-style end-of-line comments
A C++-style end-of-line comment is for shorter comments, starts with //
and ends at the end of the line.
eolComment
newlineany characters
newline
not
//
1001ICT Introduction To Programming – 2015-2 621
I.2.3 Identifier and keywords
Identifiers
MaSH programmers create new names for their variables and constants.
These names are called identifiers.
Identifiers start with a letter, which may then be followed by additional
letters, digits or underscores (_).
identifier
letter
digit
_
letter
1001ICT Introduction To Programming – 2015-2 622
Keywords
Some words, made up only of letters and therefore meeting the description
of identifiers given above, are special keywords in the Java language (and
some of them in MaSH too) and therefore can not be used as names for
variables, constants and methods.
1001ICT Introduction To Programming – 2015-2 623
The full list of these reserved words or keywords is given in the following
table.
abstract else interface switch
assert enum long synchronized
boolean extends native this
break false new throw
byte final null throws
case finally package transient
catch float private true
char for protected try
class goto public void
const if return volatile
continue implements short while
default import static
do instanceof strictfp
double int super
1001ICT Introduction To Programming – 2015-2 624
I.2.4 Literals
Literals represent a value explicitly. Every literal has a type.
literal
integerLiteral
floatingLiteral
booleanLiteral
characterLiteral
stringLiteral
1001ICT Introduction To Programming – 2015-2 625
I.2.5 Integer literals
Integer literals may be written in decimal, hexadecimal or octal. An l or L
at the end of the integer literal, means that the type on the integer is long.
By default, the type is int unless the value is too big to fit in an int.
integerLiteral
l
L
decimalNumeral
hexNumeral
octalNumeral
1001ICT Introduction To Programming – 2015-2 626
Unless the whole decimal numeral is just 0, a decimal numeral must not
start with a zero or it will be assumed to be an octal numeral. A non-zero
decimal numeral must start with a digit other than 0, and then more digits
may follow.
decimalNumeral
0
digit
digit
0
not
A hexadecimal numeral starts with 0x, which is followed by one or more
hexadecimal digits.
hexNumeral
hexDigit0x
1001ICT Introduction To Programming – 2015-2 627
An octal numeral starts with 0, which is followed by one or more octal
digits.
octalNumeral
octalDigit0
Floating point literals
A floating point literal is used to create values of type float or double,
for fractional, very large or very small numbers.
1001ICT Introduction To Programming – 2015-2 628
A floating point literal starts with a whole number part, then a decimal point,
then optionally the fractional digits, then optionally an e or E that intro-
duces an optionally signed exponent. An f or F at the end of the floating
point literal indicated that the type is float. A d or D at the end indicates
double. By default, the type is double.
floatingLiteral
f
F
d
D
digit
+
-
e
E
digit
.digit
1001ICT Introduction To Programming – 2015-2 629
Boolean literals
Boolean values are represented by the keywords false and true.
booleanLiteral
false
true
1001ICT Introduction To Programming – 2015-2 630
Special character escape sequences
To put some special characters in character and string literals we use a spe-
cial sequence that starts with the special escape character \ (a backslash).
The next character indicates which character the whole escape sequence is
representing.
escapeSequence
n
t
’
"
\
\ escape sequence represents a ...
\n newline character
\t tab character
\’ single quote (apostrophe)
\" double quote character
\\ backslash character
1001ICT Introduction To Programming – 2015-2 631
Character literals
A character literal, of type char,
is usually just that character dis-
played between single quotes.
The single character can’t be a
backslash, single quote or the end
of a line. Instead of a single char-
acter, you can put one of the spe-
cial character escape sequences
between the quotes.
characterLiteral
’any character
’
\
newline
not
escapeSequence
’
1001ICT Introduction To Programming – 2015-2 632
String literals
A string literal, of type
String, is usually just zero
or more characters displayed
between double quotes. The
characters can’t be back-
slashes, double quotes or the
ends of lines. Strings can
also contain the special char-
acter escape sequences.
stringLiteral
"
any character
"
\
newline
not
escapeSequence
"
1001ICT Introduction To Programming – 2015-2 633
I.2.6 Separators
Separators are the punctuation symbols of the language.
separator
(
)
{
}
[
]
;
,
1001ICT Introduction To Programming – 2015-2 634
I.2.7 Operators
These symbols made up of one or more special characters
are represent actions like addition and assignment.
operator
+
-
*
/
%
==
<=
>=
>
<
!=
!
&&
||
=1001ICT Introduction To Programming – 2015-2 635
I.2.8 A MaSH input source
A MaSH input source (a mash program) is made up of a sequence of these
elements in any order (as far as the lexical syntax is concerned): whites-
pace; comments; literals; identifiers (including keywords); separators; and
operators.
mashSource
whitespace
comment
literal
identifier
separator
operator
1001ICT Introduction To Programming – 2015-2 636
I.3 Context-free grammar
The MaSH context-free grammar describes how to order MaSH tokens, but
does not define the context rules (rules like “Declare a variable before using
it.”).
Because any amount of whitespace (including comments) is permitted be-
fore, after and between tokens, whitespace (including comments) is not
mentioned again in this grammar.
1001ICT Introduction To Programming – 2015-2 637
I.3.1 MaSH programs
A program begins with an import directive that selects the environment
within which this program will run.
Note that without selecting an environment, the program could not do any-
thing that the user could observe. It could not display anything or control
any hardware. The environments provide the methods by which these things
can be done.
After the import directive, comes the program in the no-method program
structure.
mashProgram
noMethodProgramimportDirective
1001ICT Introduction To Programming – 2015-2 638
No-method programs
A no-method program consists of a sequence of statements.
noMethodProgram
statement
Import directives
An import directive starts with the keyword import, which is followed
by an identifier (the name of the environment), and ends with a semicolon.
Environment names should start with a lower case letter.
importDirective
;identifierimport
1001ICT Introduction To Programming – 2015-2 639
I.3.2 Statements
Statements are only simple statements at this level.
statement
simpleStatement
I.3.3 Simple statements
A simple statement is either: the empty statement (which does nothing); a
declaration statement; or an expression statement.
simpleStatement
emptyStatement
declarationStatement
expressionStatement
1001ICT Introduction To Programming – 2015-2 640
I.3.4 Empty statements
An empty statement does nothing and consists solely of its terminating
semicolon.
emptyStatement
;
I.3.5 Declaration statements
Declaration statements declare either constants or variables and end with a
semicolon.
declarationStatement
;variableDeclaration
constantDeclaration
1001ICT Introduction To Programming – 2015-2 641
I.3.6 Variable declarations
A variable declaration begins with a type and then introduces at least one
new variable. Multiple new variables are separated by commas. The vari-
able declaration is terminated by a semicolon.
variableDeclaration
newVariable,
newVariabletype
1001ICT Introduction To Programming – 2015-2 642
New variables
New variable introductions consist of the name of the new variable followed
optionally by the assignment operator and an expression representing the
initial value for this new variable. Variable names should start with a lower
case letter.
newVariable
orExpression=
identifier
1001ICT Introduction To Programming – 2015-2 643
I.3.7 Constant declarations
A constant declaration is much like a new variable declaration, but starts
with the keyword final. Then follows the type and then the introduc-
tions of at least one new constant. Multiple new constants are separated by
commas. The constant declaration is terminated by a semicolon.
constantDeclaration
newConstant,
newConstanttypefinal
1001ICT Introduction To Programming – 2015-2 644
New constants
New constant introductions consist of the name of the new constant fol-
lowed by the assignment operator and an expression representing the initial
value for this new variable. Unlike new variables, constants must be initi-
talised immediately and can not be assigned new values later.
newConstant
orExpression=identifier
1001ICT Introduction To Programming – 2015-2 645
I.3.8 Types
A type is the name of either a simple type or a compound or object type.
type
simpleType
objectType
1001ICT Introduction To Programming – 2015-2 646
Simple types
The simple types contain one item of logical, numeric or character data.
simpleType
boolean
byte
char
double
float
int
long
1001ICT Introduction To Programming – 2015-2 647
Object type
The only object type is the String.
objectType
String
I.3.9 Expression statements
Expression statements consist of an assignment or a method invocation fol-
lowed by a semicolon. A method invocation in this context should be a
procedure call.
expressionStatement
;assignment
methodInvocation
1001ICT Introduction To Programming – 2015-2 648
I.3.10 Assignments
An assignment is an expression that has at least one assignment operator (=)
in it. Only certain things are permitted on the left hand side of an assignment
operator. After the rightmost assignment operator comes an expression that
contains any of the other operators.
assignment
assignment
orExpression
=leftHandSide
Left hand sides
The only thing allowed on the left hand side of an assignment operator is
the name of a variable (not a constant).
leftHandSide
identifier
1001ICT Introduction To Programming – 2015-2 649
I.3.11 Method invocations
A method invocation consists of the name of the method followed by the
actual parameter list.
methodInvocation
actualParameterListidentifier
Actual parameter lists
An actual parameter list is enclosed by parentheses and contains a sequence
of zero or more expressions separated by commas.
actualParameterList
)
orExpression,
orExpression
(
1001ICT Introduction To Programming – 2015-2 650
I.3.12 Expressions
The grammar for expressions defines the order of precedence of the vari-
ous operators. The lowest precedence operator is the assignment operator
(already dealt with above), the next lowest precedence operator is the “or”
operator (||).
Or expressions
An “or” expression is a sequence of “and” expressions separated by the “or”
operator (||).
orExpression
andExpression||orExpression
andExpression
1001ICT Introduction To Programming – 2015-2 651
And expressions
An “and” expression is a sequence of “equals” expressions separated by the
“and” operator (&&).
andExpression
equalsExpression&&andExpression
equalsExpression
1001ICT Introduction To Programming – 2015-2 652
Equals expressions
An “equals” expression is a sequence of “less-than” expressions separated
by the “equals” operator (==) or the “not-equals” operator (!=).
equalsExpression
lessThanExpression==equalsExpression
lessThanExpression!=equalsExpression
lessThanExpression
1001ICT Introduction To Programming – 2015-2 653
Less-than expressions
A “less-than” expression is a sequence of “plus” expressions separated by
the “less-than” operator (<), the “less-than-or-equals” operator (<=), the
“greater-than” operator (>), or the “greater-than-or-equals” operator (>=).
lessThanExpression
plusExpressionlessThanExpression
plusExpression>=lessThanExpression
plusExpression
1001ICT Introduction To Programming – 2015-2 654
Plus expressions
A “plus” expression is a sequence of “times” expressions separated by the
“plus” operator (+), or the “minus” operator (-).
plusExpression
timesExpression+plusExpression
timesExpression-plusExpression
timesExpression
1001ICT Introduction To Programming – 2015-2 655
Times expressions
A “times” expression is a sequence of “unary” expressions separated by the
“times” operator (*), the “divide-by” operator (/), or the “modulo” operator
(%).
timesExpression
unaryExpression*timesExpression
unaryExpression/timesExpression
unaryExpression%timesExpression
unaryExpression
1001ICT Introduction To Programming – 2015-2 656
Unary expressions
A “unary” expression has zero or more unary operators followed by an
atomic expression. The unary operators are “plus” (+), “minus” operators
(-), “not” (!), or a type cast. A type cast is written as a simple type name
between parenetheses.
unaryExpression
unaryExpression!
unaryExpression+
unaryExpression-
unaryExpression)simpleType(
atomicExpression
1001ICT Introduction To Programming – 2015-2 657
Atomic expressions
An “atomic” expression is either: a literal; an identifier (a variable or con-
stant name); a method invocation; or an “or” expression enclosed by paren-
theses. A method invocation in this context must be of a function (not a
procedure).
atomicExpression
literal
identifier
methodInvocation
)orExpression(
1001ICT Introduction To Programming – 2015-2 658
I.4 Style conventions
These are rules all Java programmers adhere to, even if the Java compiler
does not enforce them. The MaSH compiler will warn about these things.
• Variable names must start with a lower case letter.
• Any letters in a constant’s name must be in upper case.
• All method names start with a lower case letter.
1001ICT Introduction To Programming – 2015-2 659
These are MaSH-specific rules, but are consistent with the equivalent in
Java.
• Programs are saved in files that have names that start with an upper
case letter.
• A program’s file name must match the lexical definition of an identi-
fier (with .mash added).
• All environment names are identifiers that start with a lower case let-
ter.
1001ICT Introduction To Programming – 2015-2 660
I.5 Semantic rules
I.5.1 Variables
• A variable must be declared before it is used.
• Before a variable’s value can be used it must have been assigned one.
I.5.2 Constants
• A constant must be declared before it is used.
• A constant must be assigned a value at the same time as it is declared.
• A constant may not be reassigned a second value.
1001ICT Introduction To Programming – 2015-2 661
I.5.3 Assignment compatibility
• Only a variable name may appear on the left hand side of the assign-
ment operator (=).
• The value on the right of the assignment operator must be assignment
compatible with the type of the variable on the left.
• If two types are the same, they are assignment compatible.
• If the expression on the right has a type that can automatically be
promoted by a conversion that does not lose information to the type
of the variable on the left, they are assignment compatible.
1001ICT Introduction To Programming – 2015-2 662
I.5.4 Automatic promotion and type casts
• Expressions that combine values of different types are usually only
possible where the two types are the same or one type can be pro-
moted by a conversion that does not lose information to the other
type.
• Use a type cast to force a conversion between simple types where
they are not normally permitted.
1001ICT Introduction To Programming – 2015-2 663
• This table lists all of the automatic promotions that are possible be-
cause they do not lose information.
from to from to
byte short char int
byte int char long
byte long char float
byte float char double
byte double int long
short int int float
short long int double
short float long float
short double long double
float double
1001ICT Introduction To Programming – 2015-2 664
I.5.5 Method calls
• To call a method provided by the environment, it must be passed a list
of actual parameter values that are the same or assignment compatible
with the types of parameters that the method is declared to have.
1001ICT Introduction To Programming – 2015-2 665
I.6 Section summary
This section covered:
• the complete lexical syntax of MaSH;
• the statements-level context-free grammar for MaSH;
• some coding style conventions; and
• some of the semantic rules of MaSH.
1001ICT Introduction To Programming – 2015-2 666
I.7 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 667
J The Control Level Language
J.1 Introduction
This document defines the MaSH programming language at its control level.
The control level adds control structures, such as loops and selections.
This document only describes what is different or new with respect to the
statements level.
J.2 Lexical syntax
Same as for the statements level.
1001ICT Introduction To Programming – 2015-2 668
J.3 Context-free grammar
Most of the grammar as presented for the statements level is unchanged,
except for the parts that describe statements.
J.3.1 Statements
There are now two general categories of statements: simple statements (as
in the statements level); and structured statements (new).
statement
simpleStatement
structuredStatement
1001ICT Introduction To Programming – 2015-2 669
J.3.2 Structured statements
A structured statement is either: a block; a while statement; a for state-
ment; a do-while statement; or an if-else statement.
structuredStatement
block
whileStatement
forStatement
doWhileStatement
ifElseStatement
1001ICT Introduction To Programming – 2015-2 670
J.3.3 Blocks
A block is a sequence of zero-or-more statements enclosed in a pair of
braces.
block
}
statement
{
1001ICT Introduction To Programming – 2015-2 671
J.3.4 while statements
A while statement is a loop that executes a statement repeatedly while a
boolean expression is true.
A while statement consists of the keyword while, a boolean expression
enclosed in parentheses (the loop guard or condition), followed by the state-
ment that will be repeated. That statement is usually a block.
whileStatement
statement)orExpression(while
1001ICT Introduction To Programming – 2015-2 672
J.3.5 for statements
A for statement is a loop that should be used to repeat a statement a definite
number of times.
A for statement consists of the keyword for, then a complicated three-
part definition that controls how many times the loop will execute (a for
control, defined below) enclosed in parentheses, followed by the statement
to be repeated. That statement is usually a block.
forStatement
statement)forControl(for
1001ICT Introduction To Programming – 2015-2 673
for controls
The three parts that control a for loop are: the declaration and initialisation
or reassignment of a loop counter variable; a condition (a boolean expres-
sion); and an assignment that counts off each execution of the loop state-
ment. These three things are separated by semicolons.
forControl
assignment;orExpression;variableDeclaration
assignment
1001ICT Introduction To Programming – 2015-2 674
J.3.6 do-while statements
A do-while statement is a loop that executes a statement once and then
repeats it while a boolean expression is true.
A do-while statement consists of the keyword do, the statement (usually
a block); the keyword while; a boolean expression enclosed in parenthe-
ses (the loop guard or condition), followed by a semicolon.
doWhileStatement
;)orExpression(whilestatementdo
1001ICT Introduction To Programming – 2015-2 675
J.3.7 if-else statements
An if-else statement executes a statement if a condition is true.
if the condition is not true, then the statement in an optional else part is
executed. The if-else statement starts with the keyword if, followed
by the condition in parentheses, followed by the statement (usually a block)
to execute if the condition is true. These may optionally be followed by
the keyword else and an alternate statement to execute if the condition is
false.
ifElseStatement
statementelse
statement)orExpression(if
1001ICT Introduction To Programming – 2015-2 676
J.4 Style conventions
All the conventions that apply at the statements level continue to apply.
1001ICT Introduction To Programming – 2015-2 677
J.4.1 Indenting
Each of the structured statements described above contain statements within
them. Those statements can be structured statements themselves.
All programmers use indenting to show the structure of code, that is what
statements are inside each other. The deeper inside, the more a statement is
indented.
Indenting is done with a consistent number of spaces each time. Most pro-
grammers will indent by three or four spaces. I prefer 3.
Warning: the compiler ignores the indenting. If you get the indenting
wrong, you may misunderstand the real structure of the program. Braces
may help.
1001ICT Introduction To Programming – 2015-2 678
J.4.2 Braces
Each of the structured statements described above contain single statements
within them. Usually more than one thing needs to be done, so a block is
used to make a sequence of statements appear as one.
Making a block is as simple as enclosing the statements within braces.
It is actually a good habit to use braces even when there is only one state-
ment within the structured statement. This makes the structure even clearer
and may avoid errors as extra statements get inserted later.
There is a variety of opinions about how the use of braces should be com-
bined with indenting. The examples in the next section show the most pop-
ular choices.
1001ICT Introduction To Programming – 2015-2 679
J.4.3 Examples
Code without indenting, good spacing or consistent use of braces:
import console;for(int i=0;i<10;i=i+1){for(int j=
0;j<10;j=j+1)if(i 0.
1001ICT Introduction To Programming – 2015-2 835
O.8 Sounds
Purpose
Like images, sound files can be loaded and played many times. File formats
include .wav and .aif. Others may work. Loaded sounds are identified
by an ID number.
A sound once loaded, can be played or looped. If it is played again, before
it is finished, it will start from the beginning again. Multiple sounds may be
played at the same time. A single sound file loaded multiple times may be
played at the same time.
1001ICT Introduction To Programming – 2015-2 836
Methods
int getSound (String url)
Purpose: Load a sound clip from the file at url and return its
new ID. If the ID returned is negative, the load failed.
Precondition: url is a URL, not just a file name. For example,
file:sound.wav.
void playSound (int soundID)
Purpose: Play the sound selected by soundID.
Precondition: soundID must refer to a sound that has been
preloaded with getSound(String).
1001ICT Introduction To Programming – 2015-2 837
void loopSound (int soundID)
Purpose: Loop the sound selected by soundID.
Precondition: soundID must refer to a sound that has been
preloaded with getSound(String).
void stopSound (int soundID)
Purpose: Stop the sound selected by soundID.
Precondition: soundID must refer to a sound that has been
preloaded with getSound(String).
1001ICT Introduction To Programming – 2015-2 838
O.9 Using the mouse
Purpose
Implement the rewrite methods to handle mouse events that occur within
the content area of the frame. The functions provide the mouse position at
any time.
Rewrites
void onMouseClicked (int x, int y)
Purpose: Implement this method to handle mouse clicks in the
content area of the frame.(x, y) will be the passed the coordinates of the mouse relative
to the content area of the frame at the time the event occured.
1001ICT Introduction To Programming – 2015-2 839
void onMouseEntered (int x, int y)
Purpose: Implement this method to handle the mouse entering
the content area of the frame.(x, y) will be the passed the coordinates of the mouse relative
to the content area of the frame at the time the event occured.
void onMouseExited (int x, int y)
Purpose: Implement this method to handle the mouse exiting
the content area of the frame.(x, y) will be the passed the coordinates of the mouse relative
to the content area of the frame at the time the event occured.
1001ICT Introduction To Programming – 2015-2 840
void onMousePressed (int x, int y)
Purpose: Implement this method to handle the mouse being
pressed within the content area of the frame.(x, y) will be the passed the coordinates of the mouse relative
to the content area of the frame at the time the event occured.
void onMouseReleased (int x, int y)
Purpose: Implement this method to handle the mouse being
released within the content area of the frame.(x, y) will be the passed the coordinates of the mouse relative
to the content area of the frame at the time the event occured.
1001ICT Introduction To Programming – 2015-2 841
Methods
int mouseX ()
Purpose: Returns the current horizontal ordinate x of the mouse
pointer relative to the content area of the frame.
int mouseY ()
Purpose: Returns the current vertical ordinate y of the mouse
pointer relative to the content area of the frame.
1001ICT Introduction To Programming – 2015-2 842
O.10 Keyboard events
Purpose
Implement the rewrite methods to handle keyboard events when the frame
is in focus.
The codes that identify keys may be discovered by experiment. (Write han-
dlers that print the codes to the console.) Some handy codes are those for
the arrow keys: left = 37; up = 38; right = 39; and down = 40.
1001ICT Introduction To Programming – 2015-2 843
Rewrites
void onKeyPressed (int code)
Purpose: Implement this method to handle a key being pressed
while the frame is in focus.
code will be the passed a code that identifies the key.
void onKeyReleased (int code)
Purpose: Implement this method to handle a key being released
while the frame is in focus.
code will be the passed a code that identifies the key.
1001ICT Introduction To Programming – 2015-2 844
void onKeyTyped (char c)
Purpose: Implement this method to handle a key being typed
while the frame is in focus.
c will be the passed the character that was typed.
1001ICT Introduction To Programming – 2015-2 845
O.11 Waiting for fixed times
Methods
void sleep (int ms)
Purpose: Makes the program wait for a requested number of
ms (miliseconds).
O.12 Terminating a program
Methods
void exit ()
Purpose: Terminates the program.
1001ICT Introduction To Programming – 2015-2 846
O.13 Section summary
This section covered:
• The documentation for the graphics environment, excluding stuff
that is also in console.
1001ICT Introduction To Programming – 2015-2 847
O.14 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 848
P Environment files
P.1 Purpose
This environment supports programming for a console program that reads
from standard input and writes to standard output, as per environment con-
sole, but also adds the capability to read and write files on disk.
In this version (for lecture notes), everything that is also in console is omit-
ted.
1001ICT Introduction To Programming – 2015-2 849
P.2 Opening and closing files
Purpose
These are the methods by which we open and close files.
When a file is opened, the method that opens the file will return an int, a
fileID, which identifes that file to the methods for reading or writing. If
the returned int is negative, the file could not be opened for some reason.
Files opened for reading can not be written to. Files opened for writing can
not be read from.
Files opened for reading or writing must be closed by calling the close
method before your program ends.
Files are opened by specifying the path to it. Example paths: fred.txt;
E:\holiday\itenerary.txt.
1001ICT Introduction To Programming – 2015-2 850
Methods
int openRead (String path)
Purpose: openRead(path) opens the file at path for read-
ing and returns the unique ID by which this file may be ac-
cessed. IDs are always non-negative. If a negative number is
returned, the file could not be opened.
Precondition: There must be a file at path to read from.
1001ICT Introduction To Programming – 2015-2 851
int openWrite (String path)
Purpose: openWrite(path) opens the file at path for writ-
ing and returns the unique ID by which this file may be ac-
cessed. IDs are always non-negative. If a negative number is
returned, the file could not be opened. If there is an existing file
at path, its contents are discarded.
void close (int fileID)
Purpose: close(fileID) closes the file selected by fileID.
1001ICT Introduction To Programming – 2015-2 852
P.3 Reading from files
Purpose
The following are methods for reading from files and for checking to see if
there is more input to read from them.
1001ICT Introduction To Programming – 2015-2 853
Methods
int readInt (int fileID)
Purpose: Returns the next integer from the file selected by
fileID.
Precondition: fileID selects a file that is open for reading.
Precondition: Will cause a run time error unless there is an in-
teger in the file to read. Use isNextInt(fileID) to check
first.
1001ICT Introduction To Programming – 2015-2 854
long readLong (int fileID)
Purpose: Returns the next long from the file selected by fileID.
Precondition: fileID selects a file that is open for reading.
Precondition: Will cause a run time error unless there is a long
in the file to read. Use isNextLong(fileID) to check
first.
1001ICT Introduction To Programming – 2015-2 855
boolean readBoolean (int fileID)
Purpose: Returns the next boolean from the file selected by
fileID.
Precondition: fileID selects a file that is open for reading.
Precondition: Will cause a run time error unless there is a
boolean in the file to read. Use isNextBoolean(fileID)
to check first.
1001ICT Introduction To Programming – 2015-2 856
double readDouble (int fileID)
Purpose: Returns the next double from the file selected by
fileID.
Precondition: fileID selects a file that is open for reading.
Precondition: Will cause a run time error unless there is a dou-
ble in the file to read. Use isNextDouble(fileID) to
check first.
1001ICT Introduction To Programming – 2015-2 857
float readFloat (int fileID)
Purpose: Returns the next float from the file selected by fileID.
Precondition: fileID selects a file that is open for reading.
Precondition: Will cause a run time error unless there is a float
in the file to read. Use isNextFloat(fileID) to check
first.
1001ICT Introduction To Programming – 2015-2 858
String readWord (int fileID)
Purpose: Returns the next word as a String from the file
selected by fileID. A “word” is a sequence of one-or-more
non-whitespace characters.
Precondition: fileID selects a file that is open for reading.
Precondition: Will cause a run time error unless there is a word
in the file to read. Use isNextWord(fileID) to check
first.
1001ICT Introduction To Programming – 2015-2 859
String readLine (int fileID)
Purpose: Returns the next line of text as a String from the
file selected by fileID. A line is a sequence of zero-or-more
characters terminated by the end of line, which is not returned
as part of the line.
Precondition: fileID selects a file that is open for reading.
Precondition: Will cause a run time error unless there is a line
in the file to read. Use isNextLine(fileID) to check
first.
1001ICT Introduction To Programming – 2015-2 860
boolean isNextInt (int fileID)
Purpose: Returns true if and only if there is an integer in the
file selected by fileID available to read, that is readInt(fileID)
would succeed.
Precondition: fileID selects a file that is open for reading.
boolean isNextLong (int fileID)
Purpose: Returns true if and only if there is a long in the file
selected by fileID available to read, that is readLong(fileID)
would succeed.
Precondition: fileID selects a file that is open for reading.
1001ICT Introduction To Programming – 2015-2 861
boolean isNextBoolean (int fileID)
Purpose: Returns true if and only if there is an boolean in the
file available to read, that is readBoolean(fileID)would
succeed.
boolean isNextDouble (int fileID)
Purpose: Returns true if and only if there is a double in the
file selected by fileID available to read, that is
readDouble(fileID) would succeed.
Precondition: fileID selects a file that is open for reading.
1001ICT Introduction To Programming – 2015-2 862
boolean isNextFloat (int fileID)
Purpose: Returns true if and only if there is a float in the file
selected by fileID available to read, that is readFloat(fileID)
would succeed.
Precondition: fileID selects a file that is open for reading.
boolean isNextWord (int fileID)
Purpose: Returns true if and only if there is a word in the file
selected by fileID available to read, that is readWord(fileID)
would succeed.
1001ICT Introduction To Programming – 2015-2 863
boolean isNextLine (int fileID)
Purpose: Returns true if and only if there is a line in the file
selected by fileID available to read, that is readLine(fileID)
would succeed.
Precondition: fileID selects a file that is open for reading.
1001ICT Introduction To Programming – 2015-2 864
P.4 Writing to files
Purpose
The following are methods for printing to files.
Methods
void print (int fileID, char c)
Purpose: Writes character c to the file selected by fileID.
Precondition: fileID selects a file that is open for writing.
1001ICT Introduction To Programming – 2015-2 865
void print (int fileID, String s)
Purpose: Writes string s to the file selected by fileID.
Precondition: fileID selects a file that is open for writing.
void print (int fileID, long i)
Purpose: Writes integral i to the file selected by fileID.
Precondition: fileID selects a file that is open for writing.
1001ICT Introduction To Programming – 2015-2 866
void print (int fileID, boolean p)
Purpose: Writes boolean p to the file selected by fileID.
Precondition: fileID selects a file that is open for writing.
void print (int fileID, double x)
Purpose: Writes floating point number x to the file selected by
fileID.
Precondition: fileID selects a file that is open for writing.
1001ICT Introduction To Programming – 2015-2 867
void println (int fileID, char c)
Purpose: Writes character c and then a newline to the file se-
lected by fileID.
Precondition: fileID selects a file that is open for writing.
void println (int fileID, String s)
Purpose: Writes string s and then a newline to the file selected
by fileID.
Precondition: fileID selects a file that is open for writing.
1001ICT Introduction To Programming – 2015-2 868
void println (int fileID, long i)
Purpose: Writes integral i and then a newline to the file se-
lected by fileID.
Precondition: fileID selects a file that is open for writing.
void println (int fileID, boolean p)
Purpose: Writes boolean p and then a newline to the file se-
lected by fileID.
Precondition: fileID selects a file that is open for writing.
1001ICT Introduction To Programming – 2015-2 869
void println (int fileID, double x)
Purpose: Writes floating point number x and then a newline to
the file selected by fileID.
Precondition: fileID selects a file that is open for writing.
1001ICT Introduction To Programming – 2015-2 870
P.5 Command line arguments
Purpose
These methods give access to the command line arguments.
Methods
String[] args ()
Purpose: Returns the array of command line agruments.
int numArgs ()
Purpose: Returns the number of command line arguments.
1001ICT Introduction To Programming – 2015-2 871
P.6 Section summary
This section covered:
• The documentation for the files environment, excluding stuff that
is also in console.
1001ICT Introduction To Programming – 2015-2 872
P.7 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 873
Q Standard Streams and Redirection
This appendix explains the standard streams provided to console programs
and how to run programs that use them in flexible ways.
1001ICT Introduction To Programming – 2015-2 874
Q.1 Standard streams
Modern operating systems automatically set up console programs with a
connection to the keyboard and to the display screen, treating each as just a
stream of characters.
These streams are named:
standard input – the stream of input, normally typed by the user at the
keyboard;
standard output – the stream of text output by program, usually to the
screen; and
standard error – the stream of text error messages output by program,
also usually to the screen.
1001ICT Introduction To Programming – 2015-2 875
Q.2 Simulating end-of-file
A program that reads from the keyboard can be programmed to read to the
end of the input file (even though it is not really a file).
On Unix, Linux and Mac systems, simulate end-of-file by typing a Control-
D at the start of a line. On Windows, use a Control-Z.
To demonstrate, this (and redirection, below), use the Cat program, which
is unix’s cat tool written in MaSH. Used this way, Cat just echoes what
you type until you simulate end-of-file.
] java Cat
I like the sound of my own voice.
I like the sound of my own voice.
Echo!
Echo!
]
1001ICT Introduction To Programming – 2015-2 876
Q.3 Redirection
While the standard input and output streams are linked to the keyboard and
screen by default, programs can be run with the streams linked to other
sources and destinations.
1001ICT Introduction To Programming – 2015-2 877
Q.3.1 Output redirection
The standard output stream can be redirected away from the screen using a
>.
For example, to save the output to a file:
] java Cat > somefile.txt
I like the sound of my own voice.
Echo!
] ls
Cat.class Cat.java
Cat.mash somefile.txt
1001ICT Introduction To Programming – 2015-2 878
Q.3.2 Input redirection
The standard input stream can be redirected away from the keyboard using
a <.
] java Cat < somefile.txt
I like the sound of my own voice.
Echo!
]
1001ICT Introduction To Programming – 2015-2 879
Q.3.3 Appending output
The standard output stream can be appended to an existing file with >>.
] java Cat >> somefile.txt
I have a little more to say.
] java Cat < somefile.txt
I like the sound of my own voice.
Echo!
I have a little more to say.
]
1001ICT Introduction To Programming – 2015-2 880
Q.3.4 Piping
The standard output stream from one program can be piped into the standard
input stream of another program with |.
] ls | java Cat > newfile.txt
] java Cat < newfile.txt
Cat.class
Cat.java
Cat.mash
newfile.txt
somefile.txt
]
Note that both programs run in parallel, the second one consuming the out-
put of the first as it is produced.
1001ICT Introduction To Programming – 2015-2 881
Q.4 Filters
Programs that read and write streams of text are called filters and are very
useful, and by piping from one to another, complex tasks can be performed.
The Unix operating system has many of them, cat, tee, grep, diff,
sed, sort, wc, to name a few.
1001ICT Introduction To Programming – 2015-2 882
Q.5 Section summary
This section covered:
• the standard input, output and error streams;
• how to end keyboard input with control characters; and
• how to redirect the streams.
1001ICT Introduction To Programming – 2015-2 883
Q.6 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 884
R Reminder About Academic Misconduct
During orientation week you were informed about the issues of plagiarism,
academic misconduct and their consequences.
This section is a reminder with details specific to this course.
1001ICT Introduction To Programming – 2015-2 885
R.1 What is plagiarism?
• It is one kind of academic misconduct.
• It is cheating and stealing.
• It is an attempt to gain credit for something that is not your property,
not your idea or not your work.
• It is taking the intellectual contents produced by others and pretend-
ing that it is your own.
• If you didn’t produce it, it is not yours.
1001ICT Introduction To Programming – 2015-2 886
R.2 Plagiarism in programming
• Programming exercises are a particular problem with respect to cheat-
ing.
• They may be easily electronically duplicated and cosmetically al-
tered.
• However, the similarities can still be identified by textual analysis
programs and experienced teachers.
• Students are warned that cheating instances are detected frequently,
and must be treated seriously and promptly.
1001ICT Introduction To Programming – 2015-2 887
R.3 Other kinds of academic misconduct
• Showing other students your work.
• Electronic transmission of your work.
• Selling solutions.
1001ICT Introduction To Programming – 2015-2 888
R.4 Appropriate conduct
• You can discuss concepts, similar problems, illustrations and exam-
ples related to the project with:
– your lecturer/tutor;
– other students in the course;
– peer mentors;
– PASS leaders; or
– your course convenor.
• Your submissions must reflect the work and original contribution of
an individual student.
1001ICT Introduction To Programming – 2015-2 889
R.5 Dishonest submissions include:
• deliberate copying or attempting to copy the work of other students;
• use of or attempting to use information prohibited from use in a par-
ticular assessment;
• submitting the work of another as your own; or
R.6 Consequences of plagiarism
Instances of plagiarism will be handled according to the University’s Insti-
tutional Framework for Promoting Academic Integrity Among Students.
1001ICT Introduction To Programming – 2015-2 890
R.7 Risks
These are particular risks that have got students into trouble before.
• Private tutors that help too much with assessment items. How many
students are being “helped” in the same way?
• On-line/cloud source control, note or clipping services that are not
private. If you post assessment item code on anywhere on the net
where other students can see it you are committing academic miscon-
duct.
• On-line answer services. Asking other people to solve your home-
work is obviously academic misconduct.
1001ICT Introduction To Programming – 2015-2 891
R.8 Section summary
This section covered:
• Plagiarism is presenting someone else’s work as yours.
• Your project is individual.
• We do detect plagiarism and it has serious consequences.
1001ICT Introduction To Programming – 2015-2 892
R.9 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 893
S NXT Tips
Here are some practical tips for programming and using Mindstorms NXT
robots.
1001ICT Introduction To Programming – 2015-2 894
S.1 Know your robot
To program a robot you have to know what sensors and actuators are plugged
into what ports.
This information for the robots we use in the course is available on the
course web site at:
http://www.ict.griffith.edu.au/arock/itp/students/
robots/
There is usually advice as to what direction the robot will move when you
call motorForward(...) or motorBackward(...).
1001ICT Introduction To Programming – 2015-2 895
S.2 Sleep after setting up sensors
Some sensors do not return sensible values straight after they are set up and
turned on with setUpSensor(...).
This applies to light, sound, and proximity sensors.
It does not apply to touch and rotation sensors.
After calling setUpSensor(...), allow the sensor to stabilize by wait-
ing for half a second, like this:
setUpSensor(...); // fill in the port and sensor
sleep(500);
// now do stuff
1001ICT Introduction To Programming – 2015-2 896
S.3 Place the robot on the track – first
Simple robot programs usually only work well if the robot starts in its as-
sumed position and conditions.
In particular, if a robot is using light sensors to detect light and dark areas
on a track, do not start the robot program until the robot has been placed in
the correct position on the track.
If you start the program holding the robot up in the air, it will likely behave
as if it is seeing a very dark light level. The program will not then work as
expected after the robot is put down on the track.
1001ICT Introduction To Programming – 2015-2 897
S.4 Sleep after stopping
As soon as a program finishes, all power is cut to motors. So if you want a
robot to come to a precise stop, and not to keep rolling, stop the motors and
allow them to have time to brake the robot before the program ends.
// robot is moving
motorStop(...); // fill in the port
sleep(1000);
// end of program
1001ICT Introduction To Programming – 2015-2 898
S.5 Sound sensors hear motors
If you’re using a sound sensor and the motors are running, the sound sensor
will hear the motors.
The motor may sound a lot louder to the sensor than you, because vibration
will be transmitted through the frame of the robot from the motor to the
sensor.
1001ICT Introduction To Programming – 2015-2 899
S.6 The Format command
You can only load so many files into the NXT.
When it’s full, use the Lejos command System ▶ Format to wipe all of
the program files in one go.
1001ICT Introduction To Programming – 2015-2 900
S.7 Reassembling after changing batteries
Some of the robots need to be partially disassembled to change batteries.
Here are some tips:
• Don’t unplug the cables. You can turn the NXT over to access the bat-
teries without doing this. Leaving them plugged in avoids plugging
them back into the wrong ports.
1001ICT Introduction To Programming – 2015-2 901
• Connections with pins are easier to put back together if the pins are
all on the same side. Examples:
difficult easy
1001ICT Introduction To Programming – 2015-2 902
S.8 Section summary
This section covered:
• Practical tips for using and programming an NXT.
1001ICT Introduction To Programming – 2015-2 903
S.9 End of section feedback questions
Send us your answers to these questions any time you like by clicking on
them.
• What was the most useful topic in this section?
• What was the least useful topic in this section?
• What was the least clear topic in this section?
• What topic in this section would you like to know more about?
• Did you find an error in this section?
1001ICT Introduction To Programming – 2015-2 904