There are two reasons that programming is difficult to learn. The first is that when you write a program you have to tell the computer exactly what to do. If you are imprecise or leave out any instruction then the program will not work. Humans don't need to be so precise in normal day to day living and this takes some getting used to.
The second reason is you must be able to think about the problem as a human sees it (high level view) and as the computer sees it (the low level view) and possibly many intermediate stages as well. Typical problems that are solved by computers are too complex if viewed at a low level all the time and so the process of looking at a problem at a high level is an exercise in managing complexity. In fact many terms are applied to this process of managing complexity, some that you'll here on this course are problem subdivision, modular programming and most especially object-oriented programming.
This ability to view a problem at many different levels is difficult, but we will teach you effective techniques to manage it.
So how are we going to teach you to program. Well initially we'll be using robots. You'll have to move robots around a screen. This is a very good practice at low level programming. You'll be programming the robots in Java so you will also be developing your knowledge of the Java programming language. This will occupy the first few weeks of the module.
Then we'll move on to small stand alone Java programs. During this period we'll cover
For example, you were selected for this course (Computer Applications at DCU) by a computer program. This program allocates places on a particular course to students with appropriate points. In this program, each student would have been an object, as would each university and each course. There might have been other objects as well.
This course is an introductory course in programming and won't be concerned about design, but you need to know a little about objects because Java is an object-oriented programming language.
In Java an object type is introduced using the class keyword. Every Java program contains at least one object type (class). If this class is called House, then the Java program will be contained in a file called House.java.
class House
{
}
|
House.java is called the Java or the source file, House.class is called the class file.
In the next section we will create useful programs and explain how a program works.
An example RobotWorld is can be seen in the diagram to the right.
Some of the ideas of RobotWorld have been borrowed from the book Karel the Robot, A Gentle Introduction to the Art of Programming by Pattis, Roberts, and Stehlik. The programs that make up robot world are based largely on the work of Jonathan M. Bourgeois.
public class RobotProgram extends RobotWorld
{
public void setWorld()
{
wall(1, 4, "east", 10);
}
}
|
The above program creates a RobotWorld which has a wall 10 cells in length that starts at (1,4) and ends at (9,4), a cell 10 places to the east.
We'll look at the program in a minute, but first let's look at the steps required to run it. (There is also a more detailed list of instructions that you may prefer.)
public class RobotProgram extends RobotWorldMost RobotWorld programs start this way. You give the class a name (in this case RobotProgram) and extend RobotWorld.
The class is always surrounded by an opening brace { and a closing brace } as shown below.
{
:
:
}
The braces contain the definition of the class. In this class one method is defined: setWorld(). A Method is a set of instructions to accomplish a task. Here there is just one instruction, wall(1, 4, "east", 10) in the setWorld() method. For the moment, most methods you encounter will be of the form
public void methodName()Methods also surround their contents (i.e. instructions) with braces
public void setWorld()
{
wall(1, 4, "east", 10);
}
The rules for these methods are part of the Java syntax which will be explained later.
Here are some other points to note:
wall(1, 4, "east", 10); // Create a wall of length 10 units
| Here is an example of a RobotWorld. It's very simple, containing a wall of three cells starting at coordinates 19, 0 and going north (up the diagram). (The wall is in the lower right corner of the world.) | ![]() |
This was created by the following program, ShortWall.java.
public class ShortWall extends RobotWorld
{
public void setWorld()
{
wall(19, 0, "north", 3);
}
}
|
The instruction wall(19, 0, "north", 3) contains four arguments. These arguments vary the effect of the instructions. The first two arguments 19 and 0 specify the starting cell. The next argument, "north" is surrounded in quotes and specifies the direction (north/up) and the final argument specifies the length of the wall. Note that this instruction is exactly equivalent to
wall(19, 2, "south", 3);I.e. a wall starting at cell (19,2) and going down three squares will obviously be the same as a wall starting at (19,0) and going up three squares. The following two instructions also create the same wall.
wall(19, 0, "north", 1); wall(19, 1, "north", 2);By choosing the arguments appropriately, you can place a wall wherever you please. Experiment by changing the arguments and observing the effects.
| Adapt the program so that it creates a wall going east from coordinates 7, 6 for two cells. It should look like the RobotWorld on the right. N.B. the name of the class must match the name of the file, e.g. if your class is called EastWall the file must be called EastWall.java | ![]() |
When you have adapted the program, follow the instructions to compile and run it. When it is working, submit it. (Press the submit button and select the program file.) It will then be automatically marked. (The marking program may take a few minutes.)
This RobotWorld contains a square wall surrounding a beeper.
The beeper is represented by an orange circle and is placed at cell
(4,16) using the command beeper(4,16)The program WallRoundBeeper.java (see below) created this world |
![]() |
public class WallRoundBeeper extends RobotWorld
{
public void setWorld()
{
wall(2, 18, "east", 4); // topmost wall
wall(6, 18, "south", 4); // rightmost wall
wall(6, 14, "west", 4); // bottom wall
wall(2, 14, "north", 4); // left wall
// Now place a beeper in the centre
beeper(4, 16);
}
}
|
| Adapt the program (or write a new program) so that it creates a wall that surrounds four beepers as shown in the RobotWorld on the right. | ![]() |
This time you'll need an extra class to describe your robot. Also the setWorld method will have to create an instance of the robot and place it in the world.
Looking at the Robot class first, it has the same form as the RobotWorld class, except that it extends Robot (instead of RobotWorld):
public class FirstRobot extends Robot
{
public void run()
{
move();
move();
turnLeft();
move();
move();
turnOff();
}
}
And instead of a setWorld() method it has a run() method.
This run() method contains the instructions for the robot.
In this case, as soon as the robot starts, it will move forward two squares,
turn left and then move forward two more squares before terminating.
Now let's look at the ExampleProgram class. The setWorld() method creates an instance of FirstRobot called jim and then places it in the world.
class ExampleProgram extends RobotWorld
{
public void setWorld()
{
FirstRobot jim = new FirstRobot(); // Create a new robot called jim
jim.place(4, 8, "north"); // place it in the RobotWorld
}
}
An instance of a FirstRobot can be created using the new keyword.
FirstRobot jim = new FirstRobot();The expression new FirstRobot() creates an instance of FirstRobot. The first part of the instruction, FirstRobot jim, says that jim is a name that can refer to any object of type FirstRobot. In short the statement says that jim is a FirstRobot.
The next statement
jim.place(4, 8, "north");places the robot at cell (4,8) facing north.
Now if you run the program, you will see the robot at cell (4,8) and that it is facing north. If you press the run button it will execute all the instructions until it encounters the turnOff() instruction. If you run the program again, you can try the step button. This will only execute one instruction at a time.
| In this example a robot is created (the blue 'V' shape at coordinates 2, 2). If you compile and run the program (MoveRobot.java below) you will see the world to the right. | ![]() |
If you now press the run button (or press the step button many times) you will see the robot execute the instructions in the run() method and end up (see diagram). | ![]() |
public class MoveRobot extends RobotWorld
{
public void setWorld()
{
MovingRobot jim = new MovingRobot(); // create a new robot
// place it in the world at location 2, 2 facing east.
jim.place(2, 2, "east");
}
}
class MovingRobot extends Robot
{
public void run()
{
move();
move();
turnLeft();
move();
move();
turnOff();
}
}
|
When you run the program and press the run button, the run() method starts. The six instructions are carried out one after the other until the robot finishes. Note that the path that the robot takes is indicated by the red dots.
| Adapt the program so that the robot starts at location 4, 8 facing north. Use the same run() method. Where will the robot end up? |
public class OneWorld extends RobotWorld
{
public void setWorld()
{
LongRobot jane = new LongRobot(); // create a new robot
jane.place(5, 14, "south");
}
}
class LongRobot extends Robot
{
public void run()
{
turnLeft();
turnLeft();
turnLeft();
turnLeft();
move();
move();
turnOff();
}
}
|
public class SixWorld extends RobotWorld
{
public void setWorld()
{
wall(3, 14, "east", 5);
wall(3, 13, "south", 5);
wall(4, 9, "east", 4);
wall(5, 11, "east", 3);
wall(7, 10, "east", 1); // direction irrelevant when length is one.
}
}
|
public class BeeperWorld extends RobotWorld
{
public void setWorld()
{
wall(3, 14, "east", 5);
wall(3, 13, "south", 5);
wall(4, 9, "east", 4);
wall(5, 11, "east", 3);
wall(7, 10, "east", 1);
beeper(0,0);
Beep beepCatcher = new Beep();
beepCatcher.place(0, 4, "south");
}
}
class Beep extends Robot
{
public void run()
{
// First move to where the beeper is
move();
move();
move();
move();
pickBeeper(); // pick up the beeper
// Turn around
turnLeft();
turnLeft();
// Move up
move();
move();
putBeeper(); // drop the beeper at this cell.
// turn right
turnLeft();
turnLeft();
turnLeft();
move();
turnLeft();
turnOff();
}
}
|
However you can also write your own methods. For example, wouldn't it be nice to have a turnRight() instruction instead of having to use three turnLeft() instructions? Well you can create a turnRight method that executes three turnLeft() instructions:
public void turnRight()
{
turnLeft();
turnLeft();
turnLeft();
}
If you add this method to your robot class definition (before or after the
run() method) then the run() method can use the turnRight()
instruction.
Similarly, you might be tired of typing lots of move() instructions. Well you could have add moveFour() method that calls individual move() instructions:
public void moveFour()
{
move();
move();
move();
move();
}
This method would be added to the definition of your robot class.
To see a complete example, here is a program that defines and uses both
these methods.
class TestWorld extends RobotWorld
{
public void setWorld()
{
PowerRobot jane = new PowerRobot(); // create a new robot
jane.place(5, 14, "south");
}
}
class PowerRobot extends Robot
{
public void run()
{
moveFour();
moveFour();
turnLeft();
moveFour();
turnRight();
moveFour();
move();
turnRight();
}
public void turnRight()
{
turnLeft();
turnLeft();
turnLeft();
}
public void moveFour()
{
move();
move();
move();
move();
}
}
|
Remember to divide the problem into more manageable subtasks.
public class FieldOBeepers extends RobotWorld
{
public void setWorld()
{
// create a rectangle of beepers
beeper(10,4);
beeper(11,4);
beeper(12,4);
beeper(13,4);
beeper(14,4);
beeper(10,5);
beeper(11,5);
beeper(12,5);
beeper(13,5);
beeper(14,5);
beeper(10,6);
beeper(11,6);
beeper(12,6);
beeper(13,6);
beeper(14,6);
beeper(10,7);
beeper(11,7);
beeper(12,7);
beeper(13,7);
beeper(14,7);
beeper(10,8);
beeper(11,8);
beeper(12,8);
beeper(13,8);
beeper(14,8);
Harvester fred = new Harvester();
fred.place(9, 4, "east");
}
}
class Harvester extends Robot
{
public void run()
{
}
}
|
N.B. your robot should finish ready to consume another row of beepers at square (9, 9).
What we want are some instructions to tell us if there is a wall in front, or maybe we would want to know which direction we're facing. We might like to know whether there was a beeper in our cell. The following methods give us information about the world
These methods can be used in the if and while statements.
Note that you should only supply the Robot class, the RobotWorld will be supplied by RoboProf.
For example, the following code fragment moves a robot forward as long as the cell in front is clear.
while(frontIsClear())
move();
|
| This code can also be expressed in a flow Chart | ![]() |
The table below summarizes the while statement. Every time we come to a major Java statement we will summarize it in a similar way.
| Syntax |
while(condition)
statement
|
|---|---|
| Example |
while(frontIsClear())
move();
|
| Purpose | To execute a statement while a condition is true. |
public class Bouncer extends Robot
{
public void run()
{
// First move to an obstruction
while(frontIsClear())
move();
// turn around
turnLeft();
turnLeft();
// move forward two squares
move();
move();
turnOff();
}
}
|
NB you should submit a class that extends Robot (not RobotWorld). You can test your program by creating a Tester class that extends RobotWorld and has a setWorld() method that creates a new instance of your class and then places it in the world.
Note that your program will be tested by putting it into one or more unknown worlds and observing where it ends up.
Boolean values are values that can be true or false. All the methods that can "see" in the RobotWorld return boolean values. There are certain boolean operators that can be used with these boolean values. These operators are AND, OR and NOT and are represented by the characters &&, || and ! respectively.
How do you apply these? Well say you want to keep turning until you are facing east. There's a method, facingEast(), that will tell us whether we are facing east or not. We would like to keep turning until we are facing east, so the code would be
while(NOT facingEast())
turnLeft();
The idea is that you keep turning, eventually (after at most three turns) you will be facing east and the loop will exit.
This code is in fact illegal, you'd have to replace the NOT with a !, so the code becomes
while(!facingEast())
turnLeft();
Sometimes you might want to move forward as long as the cell in front was clear and as long as there was a beeper in the cell. How would you do that? That's where the AND operator (&&) comes in:
while(frontIsClear() && beepersPresent())
move();
This will cause a robot to move as long as the cell in front is clear and there is a beeper in the current cell.
If the robot reaches an obstruction and there's a beeper present, then it should stay there.
Give the Robot a run() method that will locate the beeper, pick it up and then bring it home (to the origin). You should leave the robot facing north.
Hints
public boolean wallToLeft()
{
turnLeft(); // turn to face the potential wall
if(frontIsClear()) // is there a wall there?
{
turnRight(); // go back to where we were
return false; // indicate that there was no wall
}
else // ... otherwise
{
turnRight();// go back to where we were
return true; // there is a wall.
}
}
|
This method can now be used to check if a robot has a wall to its left. (Note you'll also have to define the turnRight method for this to work.)
The following Robot has a run method that hugs a wall as long the way in front is clear.
public class WallHugger extends Robot
{
public void run()
{
// this while statement uses the logical AND
// operator to check two conditions at once
while(frontIsClear() && wallToLeft())
move();
turnOff();
}
}
|
The biggest difference that you will notice is that the Robot class started executing at the run() method whereas standard Java programs start at a main() method.
This main method has the following declaration
public static void main(String []args)We'll look at the various parts of this declaration later but from now on, every stand-alone Java program that you write will have a main() method.
Note that to use some of these programs you have to add
G:\lang\java\classesto your classpath. Your complete CLASSPATH should then be
G:\lang\java\classes;g:\lang\java\classes\robot.jar;.
| Hi There |
Here are some hints to help you create the program:
// Hello.java
// written by CDaly
public class Hello
{
public static void main(String [] args)
{
System.out.println("Hello");
}
}
|
First, let's look at another program (Line numbers have been added for clarity)
|
In line 5 we use the print method to print a number and in line 7 the computer performs a simple calculation. (* is the multiplication operator.)
Some other points
System.out.print(5 * 5);and
System.out.print("5 * 5");
each produce a different output. Try each of them to see the difference.
The quotation marks tell the computer to print whatever occurs between them
exactly as shown.
The three print methods from the program can be combined into one statement
System.out.print(5 + " squared is " + 5 * 5);
Here are some other expressions
| Expression | Comment |
|---|---|
| 11 | Constant expression |
| 21 / 3 | 21 divided by 3 |
| 2 + 4 | |
| 5 - 3 | |
| 8 % 3 | 8 mod 3 (i.e. the remainder after 8 has been divided by 3) |
|
// Square.java
// written by CDaly
public class Square
{
public static void main(String [] args)
{
System.out.print("Enter a number: ");
int n = Console.readInt();
System.out.println(n + " squared is " + n * n);
}
}
|
The first statement of this program declares an integer variable number. The Console.readInt() method causes the program to wait until the user types something at the keyboard followed by the enter key.
Compile and run this program and type a number when prompted. The computer will print the square of this number. You might think that this is not very useful, but any scientist 50 years ago would be astounded that a machine could so easily calculate the square of a number.
int number;The first part of the statement contains the type of the variable, in this case an int, or an integer. This is a whole number (i.e. it has no fractional part) which can be positive or negative, e.g. 7, 2000, -1 or 11. The second part of the declaration contains the name in this case number, which will be used to refer to the variable.
Some points to note
number = 24;Note that this is not the mathematical equals sign, it is the assignment operator. The assignment statement assigns the value of an expression (in this case 24) to a variable (in this case number).
Here are some more assignment statements:
n = 5 * 2; n = 2 * (5 + 3); sum = n + 2; n = (sum - 4 * 5) / 2;Notice that a variable can be assigned to an expression that contains another variable e.g. sum = n + 2;. In fact you can have
sum = sum + 3;The assignment operator assigns or gives the value of the expression on the right to the variable on the left. The expression on the left can be any expression of a definite value, including the variable on the left if it has already been given a value.
In the statement sum = sum + 3 the assignment operator causes three to be added to whatever sum previously contained. The following section of code:
int i; i = 2; i = i + 1; System.out.println(i);;would print 3.
The statement i = i + 1; increases the value of i by one and is called incrementing the value of i or simply incrementing i. This is a very common operation and even has a special shorthand: i++.
An assignment statement always has the form
LValue = RValue;where the LValue is always a variable, and the RValue is always an expression.
int age = 20;or
int sum = 0;Another shorthand is to declare several variables in a line. In this case commas separate the variables:
int i, j, k;When declaring variables in this way, you can also assign values to them. E.g.
int i = 9, j = -2, k = 0;
e.g. A sample run would look like
Enter a number: 4 4 doubled is 8In this case the user entered 4, the computer doubled it to get 8 and printed the answer.
Here is an example program that reads a number from the keyboard and prints three times that number. Note that the Console class is used to read from the keyboard. To use the Console class, you should set the CLASSPATH to be G:\lang\java\classes\;..
// Input.java
// written by CDaly
public class Input
{
public static void main(String [] args)
{
System.out.print("Enter a number: ");
int n = Console.readInt();
System.out.println(n + " trebled is " + 3 * n);
}
}
|
| // Declare y | |
| int y; | |
| y = 5; | |
| y = 7; | |
| y = y + 3; |
| // Declare the variables | |||
| int x; | |||
| int y; | |||
| int sum; | |||
| x | y | sum | |
|---|---|---|---|
| x = 5; | |||
| y = x + 7; | |||
| y = y + x; | |||
| sum = x * 3 + y; | |||
| Data type | Description | Range (on a 32 bit computer) | Examples |
|---|---|---|---|
| int | Integer, a whole number | -231 to 231-1 (approx. +/- 2 billion) | 5, -1, 4 |
| float | Floating point number | 1038 to 10-38 | 3.14f, 8.0f -0.001f |
| double | Double precision floating point number | 10308 to 10-308 | 3.14, 8.0 -0.001 |
| char | Character - e.g. a letter or a digit | 'e', '2', 'A', '?' |
Some points
| '\n' | newline |
| '\t' | Tab character |
| '\a' | Audible alert - print it to hear a beep. |
| '\b' | Back space |
| '\"' | A double quote |
| '\\' | Two backslashes represent one backslash |
Try printing out the following strings from a program (You could adapt the hello program)
"What is this\b-\b\b\b-" "What's that noise\n\a" "\tI need my space\n\t\t\t... lots of it\n\n" "Who said \"2B or not 2B\" and how does one get a quote into a string"
int numGoals; char letter; double price; price = 1.99; // A double value is assigned to a constant double price = price * 0.75; // a 25% discount numGoals = 3; // a hat trick numGoals = numGoals + 2; // Two more in injury time. letter = 'A'; // Character constants are enclosed in single quotes letter = 'z'; letter = '\a';
You won't use these types on this course (they are only mentioned here in case you come across some antique program you can't understand).
I said "No".Note that in order to print a double quote you have to use a backslash in front it (\").
First of all there are the normal arithmetic operators:
| + | Plus: addition |
| - | Minus: Subtraction |
| * | Multiplication |
| / | Division |
Most of these operators will produce expected results e.g.
| Expression | Value |
|---|---|
| 2 * 3 + 5 | 11 |
| (3 - 1) * 5 | 10 |
| (4 + 8) / 2 | 6 |
However the result of some expressions involving division can be surprising
| Expression | Value |
|---|---|
| 7 / 4 | 1 |
| 1 / 2 | 0 |
| 100 / 101 | 0 |
The reason is that all these numbers are integers and cannot have fractional parts. The result of the division is always rounded down. There are two ways to solve this problem, one is to use the float data type, e.g.
float x; x = 1.0/2.0;
This gives x a value of 0.5. Note that you must also specify floating-point numbers by using 2.0 rather than 2.
Another method is to make use of the modulus operator, %, which gives the remainder. E.g.
| Expression | Value |
|---|---|
| 8 % 3 | 2 |
| 1 % 2 | 1 |
| 100 % 101 | 100 |
Here is some code that uses the modulus operator.
int x; int y; cin >> x; cin >> y; cout << x << " divided by " << y << " is " << x / y << endl; cout << "The remainder is " << x % y << endl; |
| Expression | Value |
|---|---|
| 5 + 3 * 2 | 11 |
| (5 + 3) * 2 | 16 |
For example, in the expression 5 + 3 * 2, the operation involving multiplication is carried out first because multiplication has higher precedence than addition. You can change this order by using parentheses: (5 + 3) * 2. This causes the addition to be carried it before the multiplication. If you are not sure which operator has precedence, use parentheses.
| // Declare the variables | |||
| int x; | |||
| int y; | |||
| x | y | ||
|---|---|---|---|
| x = -7; | |||
| x = x + 3; | |||
| y = 3 - 5 * x; | |||
| y = (3 - 5 * x) % 2; | |||
| y = (3 - 5 * x) / (y + 2); | |||
e.g. If the user enters 5, the program should print
1
The Control flow instructions are used to make decisions (if and switch statements) and to perform repetitive tasks: while, for and do while statements.
// Old.java
// written by CDaly
public class Old
{
public static void main(String [] args)
{
int age;
System.out.println("Enter your age:");
age = Console.readInt();
if(age > 200)
System.out.println("That's older than me!");
if(age < 5)
System.out.println("You're a bit young for college.");
System.out.println("Have a nice day");
}
}
|
This program uses if statements to print out different messages depending on the value of age.
if statements have the form
if(expression) statement1 else statement2If expression is true, then statement1 is executed otherwise statement2 is executed. The else part is optional (and does not occur in Old.java).
So in the code
if(age < 5) cout << "You're a bit young for college.";the message is only printed if the expression age < 5 is true, so if, for example, age was 10, the message wouldn't be printed, if age was 3 it would be printed.
The expression age > 5 is called a conditional expression or Boolean expression as it can only have values true or false. These are named after George Boole, professor of Mathematics at UCC 150 years ago.
Because Java uses = as an assignment operator, it can't also use it as the equality operator, so if you want to test is age equal to 6, you use two equal signs:
if(age == 6) cout << "You're the same age as me!";The expression if(age = 6) is a common error, and you are likely to make this mistake many times. Remember that the equality test operator is two equal signs.
Conditional expressions use logical operators
|
|
Here is another example using the if statement.
// Pay.java
// written by NBrophy
public class Pay
{
public static void main(String [] args)
{
double pay, rate, hours; // Declare the variables
System.out.println("Enter hours worked :"); // Get the hours
hours = Console.readDouble();
System.out.println("Enter the rate per hour :"); // Get the hourly rate
rate = Console.readDouble();
pay = rate * hours; // calculate the pay
// if worked more than 40 hours, pay overtime
if(hours > 40)
pay = pay + (hours - 40) * rate / 2; // add another 50% for overtime
System.out.println("The pay is " + pay + " pounds.");
}
}
|
// if worked more than 40 hours, pay overtime
if(hours > 40)
{
overtime = (hours - 40) * rate / 2;
pay = pay + overtime;
}
causes both the statements within braces to be executed. The block is treated
as one statement. You can have as many statements as you like in a block,
including if you want, just one.
if(expression) statementHere the statement is indented to make it stand out. Although the compiler does not require a program to be indented, it does make the program much more readable. Any program that does not follow a consistent indentation style is much harder to read and is therefore a bad program. Please ensure that your programs are correctly indented, i.e. the indentation should help someone follow the logic of the program.
// PassFail.java
// This program prints out "Pass" or "Fail" depending on the value of mark
public class PassFail
{
public static void main(String [] args)
{
int mark;
System.out.print("Enter a mark: ");
mark = Console.readInt();
if(mark >= 40)
System.out.print("Pass");
else
System.out.print("Fail");
}
}
|
You must write a program that asks the user for a mark and if the mark is greater than or equal to 55, then print "Honour" otherwise print "Not an honour"
E.g. a sample session might be
Enter a mark: 70 Honourthe other case would be
Enter a mark: 40 Not an honour
| Mark | 85 to 100 | 70 to 84 | 55 to 69 | 40 to 54 | 0 to 39 |
|---|---|---|---|---|---|
| Grade | A | B | C | D | F |
The program Grade.java takes a mark and converts it to the appropriate grade.
// Grade.java
// This program gets a mark from the user and prints the corresponding grade
public class Grade
{
public static void main(String [] args)
{
int mark;
char grade;
System.out.print("Enter a mark: ");
mark = Console.readInt();
if(mark >= 85)
grade = 'A';
else if(mark >= 70)
grade = 'B';
else if(mark >= 55)
grade = 'C';
else if(mark >= 40)
grade = 'D';
else
grade = 'F';
System.out.println("The grade is " + grade + ".");
}
}
|
You must write a program that asks the user for a mark and prints out the grade according to the following table
| Mark | 70 to 100 | 60 to 69 | 55 to 59 | 40 to 54 | 0 to 39 |
|---|---|---|---|---|---|
| Grade | 1 | 2 | 3 | P | F |
E.g. a sample session might be
Enter a mark: 40 The grade is P.
// Calculate fine from speed if(speed > 35) fine = 30; else if(speed > 50) fine = 55; else if(speed > 65) fine = 75;What value will be assigned to fine?
Here is an example program that uses a for loop.
// written by CDaly
public class Squares
{
public static void main(String [] args)
{
int i;
for(i = 1; i <= 10; i++)
System.out.println(i + " squared is " + i * i);
}
}
|
Remember that i++ is equivalent to i = i + 1.
This short program will print
1 squared is 1 2 squared is 4 3 squared is 9 4 squared is 16 5 squared is 25 6 squared is 36 7 squared is 49 8 squared is 64 9 squared is 81 10 squared is 100The println method is called 10 times, each time with a different value if i. I.e. the println method is controlled by the for loop. Let's examine the contents of the parentheses
for(i = 1; i <= 10; i++)The first part i = 1 assigns 1 to i, the second part i <= 10 tells the loop to keep going as long as i is less than or equal to 10, and the last part i++ says that i should increase by one each time.
Try changing these values and see what happens.
| for loop | Initial value of i | Final value of i | Number of times executed |
|---|---|---|---|
| for(i = 1; i <= 10; i = i + 1) | |||
| for(i = 1; i < 10; i = i + 1) | |||
| for(i = 2; i <= 8; i = i + 1) | |||
| for(i = 0; i <= 6; i = i + 1) | |||
| for(i = -5; i < 5; i = i + 1) | |||
| for(i = 7; i < 7; i = i + 1) | |||
| for(i = 4; i <= 5; i = i + 1) |
// Dashnum.java
// This program prints out the numbers 1 to 10 separated by a dash
public class Dashnum
{
public static void main(String [] args)
{
int i;
for(i = 1; i <= 10; i++)
System.out.print(i + "-");
}
}
|
Write a program that prints the numbers 10 to 20 with each number followed by an *.
I.e. your program should print
10*11*12 ... 19*20*
// Numbers.java
// This program prints out the numbers n to 20 separated by a blank
// where n has been entered by the user
public class Numbers
{
public static void main(String [] args)
{
int i, n;
System.out.println("Enter a number: ");
n = Console.readInt();
for(i = n; i <= 20; i++)
System.out.println(i + " ");
}
}
|
Write a program that gets a number n from the user and prints the numbers 1 to n. Each number should be separated by a blank (' ').
A sample run might look like this
Enter a number: 6 1 2 3 4 5 6
// Sum.java
//
// This program works out the sum of the numbers from 1 to 20
public class Sum
{
public static void main(String [] args)
{
int sum = 0;
int i;
for(i = 1; i <= 20; i++)
sum = sum + i;
System.out.println("The sum of the numbers 1 to 20 is " + sum);
}
}
|
By the way, we could have avoided the for loop by using the formula
1 + 2 + 3 + ... n = n * (n-1) / 2
which would result in the following simpler program
// Sum.cpp
//
// This program works out the sum of the numbers from 1 to 20
public class Formula
{
public static void main(String [] args)
{
System.out.println("The sum of the numbers 1 to 20 is " + 20 * (20+1) / 2);
}
}
|
A sample run might look like this
Enter two numbers: 6 10 The sum is 40Note: to get two numbers from the user you could have something like this
int lower, upper; lower = Console.readInt(); upper = Console.readInt();
A sample run might look like this
Enter two numbers: 2 4 The sum of the squares is 29Note that 22 + 32 + 42 = 29
Here are some hints
First of you need a for loop to go from n1 to n2 for(int i = n1; i <= n2; i++) then you need to accumulate the squared value into a variable. Maybe something like sum = sum + (i * i) You should first initialise sum to 0,
Formally the while loop is expressed as follows
while(condition) statementThe statement will be executed as long as the condition is true. If the condition is initially false, then the statement won't be executed at all.
As with the for loop, a single statement can be replaced by a block of statements surrounded by braces.
Here is an example of pseudocode to do shopping
while (there are items on the shopping list) find the item cross it off the list
|
Another (related) rule is to use a while loop when you don't know when the loop will exit, e.g.
// Example.java
// written by CDaly
// Example using a while loop
public class Example
{
public static void main(String [] args)
{
int x = 100;
// as long as x is greater than ten, keep dividing it by two.
while(x > 10)
x = x / 2;
System.out.println("After all that, x is " + x);
}
}
|
// This program prints out the numbers 1 to 10 using a while loop
public class While
{
public static void main(String [] args)
{
int j = 1;
while(j <= 10)
{
System.out.print(j + " ");
j++;
}
}
}
|
Write a program that uses a while loop to print the numbers 5 to 15 with each number followed by a '*'.
I.e. your program should print
5*6*7*8*9*10*11*12*13*14*15*
// This program finds the factors of a number.
// Note that a for loop could be used here as well.
public class Loop
{
public static void main(String [] args)
{
int num;
System.out.print("Enter a number: ");
num = Console.readInt();
int i = 2;
while(i < num)
{
// if there is no remainder => i is a factor
if(num % i == 0)
System.out.println(i + " is a factor");
i++;
}
}
}
|
The following program checks to see if a number is prime. If a factor is found, then there is no need to check for another factor, so we can leave the loop immediately (using the break statement).
// This program checks to see if a number is prime or not
public class Prime
{
public static void main(String [] args)
{
int num;
System.out.print("Enter a number: ");
num = Console.readint();
int i = 2; // Don't count 1 when checking for primes
while(i < num)
{
if(num % i == 0)
break; // found a factor, no need to stay in the loop.
i++;
}
// Now if we exited the loop normally, then i will not
// be less than num (it will be equal), otherwise we broke
// out of the loop and num is prime.
if(i == num)
System.out.println(num + " is prime");
else
System.out.println(num + " is not prime");
}
}
|
Write a program that gets a number n from a user, and prints "Prime" if the number is prime, or 'Nonprime' otherwise.
A sample run would be
Enter a number: 7 Prime
if(age > 12 && age < 20)The other logical operator is ||, the or operator. If we want to check that someone is not a teenager then their age must be either less than 13 or greater than 19. In C++ this is
if(age < 13 || age > 19)
// written by CDaly
// this program demonstrates the use of && (the logical AND operator)
// Based on age, works out if the user is a teenager or not.
// You should test this program with various ages to ensure that it always works.
public class Teenager
{
public static void main(String [] args)
{
int age;
System.out.print("Enter your age: ");
age = Console.readInt();
if(age > 12 && age < 20)
System.out.print("You are a teenager");
else
System.out.print("You are not a teenager");
}
}
|
Note that the if statement could have been written using the || (the logical OR operator) as follows
if(age <= 12 || age >= 20)
System.out.println("You are not a teenager");
else
System.out.println("You are a teenager");
Note that the two statements are also interchanged. This is in fact an
application of De Morgan's law: you can interchange AND with OR if you
invert the logic of both cases (e.g. > becomes <=) and the logic
of the overall expression (achieved in this case by rearranging the
statements).
I.e. the following two conditions are logically inverse (if one is true, then the other is false and vice versa)
age <= 12 || age >= 20and
age > 12 && age < 20
It is sometimes useful to rearrange the logic in this way.
Now write a program that given a person's age works out if they are entitled to cheap travel on buses. To get cheap travel they must be under 16 or a pensioner (65 or over). Your program must use one if statement, and a logical operator (either && or ||)
A sample session might look like
Enter your age: 20 You must pay full fare.or
Enter your age: 70 You get cheap travel.
do {
statement1;
statement2;
} while(condition) ;
The statements within the do loop get executed at least once.
The loop will continue to be executed as long as the condition is true.
This loop is not as common as the while loop, but it is useful sometimes, such as when you want to insist that a user enter a particular type of value.
// Three.java
// written by CDaly
// this program keeps looping until the user enters a number divisible by three.
public class Three
{
public static String void main(String [] args)
{
int num;
do {
System.out.println("Enter a number: ");
num = Console.readInt();
} while(num % 3 != 0) ; // if not divisible by three, ask again
System.out.println("Thank you, " + num + " is divisible by three");
}
}
|
Here is another example
// Guess.java
// written by CDaly
// User must guess the number the computer is thinking of
public class Guess
{
public static void main(String [] args)
{
int number = 38; // user must guess this number
int guess;
do {
System.out.println("Guess a number: ");
guess = Console.readInt();
if(guess < number)
System.out.println("too low");
else if(guess > number)
System.out.println("too high");
}while(guess != number) ; // keep looping until it's correct.
// The user guessed right (or we wouldn't have got here)
System.out.println("Well Done");
}
|
// CanWork.cpp
// written by CDaly
// this program keeps looping until the user enters a normal working
// age (18 to 65)
public class CanWork
{
public static void main(String [] args)
{
int age;
do {
System.out.println("Enter a working age: ");
age = Console.readInt();
} while(age < 18 || age > 65) ; // if not valid, ask again
System.out.println("You can work at " + age);
}
}
|
Write a program that asks for a nonteen age, i.e. (less than 13 or greater than 19). A sample session might look like
nonteen: 18 nonteen: 13 nonteen: 27 Thank you, 27 is a nonteen age.
// switch.cpp
// Demo the switch statement
#include <iostream.h>
void main()
{
int choice;
cin >> choice;
switch (choice)
{
case 1:
cout << "You entered one";
break;
case 6:
cout << "You entered six";
break;
case 22:
cout << "You entered twenty two";
break;
default:
cout << "I only deal with 1, 6, and 22";
break;
}
}
|
The user enters a choice, then if it matches a particular case, the corresponding statements are executed. Note
Logical operators, && and || take two Boolean expressions and return a Boolean value e.g.
boolean finished;
finished = (i != j); // finished is true if i is not equal to j
if(!finished)
System.out.println("Not finished yet.");
the parentheses aren't necessary but make the assignment clearer.
Relational operators can also be applied to characters (chars). This can be quite a powerful technique, see for example the following code:
char c; c = Console.readChar(); if(c >= '0' && c <= '9') System.out.println(c + " is a digit"); else if(c >= 'a' && c <= 'z') System.out.println(c + " is a lowercase letter"); else if(c >= 'A' && c <= 'Z') System.out.println(c + " is an uppercase letter"); else System.out.println(c + " is not alphanumeric"; // not a digit or a letterSo although you can't multiply or divide characters, you can compare them with other characters.
// This program prints a square of asterisks
public class Square
{
public static void main(String [] args)
{
int size;
int i, j;
System.out.println("Size:");
size = Console.readInt();
// print all the rows
for(i = 0; i < size; i++)
{
// print one row of asterisks
for(j = 0; j < size; j++)
System.out.print('*');
// move to the next row
System.out.println();
}
}
}
|
Note that two index variables are required, one for each loop. In this case i is used as the index variable for the outer loop, and j is used for the inner loop.
Assuming that size is 5, then the inner loop will print a row of five asterisks. Then a new line is printed to move to the next row. The outer for loop will cause five rows to be printed.
Write a program that takes two numbers (r the number of rows and c the number of columns), and prints a rectangle of asterisks r rows by c columns.
A sample session would be
Enter the rows and columns: 2 4 **** ****
// This program prints a triangle of asterisks
public class Triangle
{
public static void main(String [] args)
{
int size;
int len, j;
System.out.println("Size:");
size = Console.readInt();
// print each row
for(len = 1; len <= size; len++)
{
for(j = 1; j <= len; j++)
System.out.print('*');
System.out.println(); // need a new line
}
}
}
|
If the value of size was 5, then this program would print
* ** *** **** *****The first time the inner loop is executed, len is 1, so only one asterisk is printed. The second time, len is 2 so two asterisks are printed and so on until len is five and five asterisks are printed.
A sample session would be
Size: 4 **** *** ** *
You can break out of any of the loops using the break statement. There is a similar but rarer continue statement which stops executing loop statements, but moves to the start of the loop ready to execute the next batch. In the case of the for loop, continue causes the index variable to be updated also.
An array is declared as follows
int [] age = new age[20];This declares an array named age of 20 integers, and is equivalent to creating 20 integer variables, age[0] to age[19]. (Note that arrays start at zero.)
Here are two more examples
char [] name = new char[10]; // an array of 10 characters double [] results = new double[365]; // an array of 365 doublesEach element of the array can be accessed using an index variable, so to print out all the ages you could use
int i; for(i = 0; i < 20; i++) System.out.println(age[i]);Here i is the index variable, and the ith element is accessed using age[i]. Note that the first element is age[0].
Like the simpler data types, arrays can be initialised when they are declared.
int [] age = {16, 12, 28, 15};
In this case, the array has been initialised, and the array has the following values
|
// initialises and prints out an array
public class ArrayPrint
{
public static void main(String [] args)
{
int [] age = {23, 19, 2, 6};
System.out.println("index\tage"); // index tab age. (Note tab is '\t')
for(int i = 0; i < age.length; i++)
System.out.println(i + "\t" + age[i]);
}
}
|
Change the declaration line of the program so that the array becomes 25, 7, 200, 2, 9.
I.e. the program should output
index age 0 25 1 7 2 200 3 2 4 9
public class ArrayInput
{
public static void main(String [] args)
{
int [] num = new int[4]; // declare an array of four integers
System.out.print("Enter four numbers: ");
int i;
for(i = 0; i < num.length; i++)
num[i] = Console.readInt(); // read in each number
System.out.println(); // print a new line
// Another for loop prints them out
for(i = 0; i < num.length; i++)
System.out.print(num[i] + " ");
}
}
|
The above program prints each number with a space after it. Adapt the program so that each number is printed with an asterisk after it.
A sample program run would look like
Enter four numbers: 23 56 3 -1 23*56*3*-1*
public class ArrayDouble
{
public static void main(String [] args)
{
int [] num = new int[3];
System.out.print("Enter three numbers: ");
for(int i = 0; i < num.length; i++)
num[i] = Console.readInt(); // read in each number
System.out.println(); // print a new line
// Multiply each number by 2 and print it out
for(int i = 0; i < num.length; i++)
System.out.println(num[i] * 2);
}
}
|
The above program prints two times each element. Adapt the program so that three times each element is printed
A sample program run would look like
Enter three numbers: 5 3 -1 15 9 -3
public class ArrayTwice
{
public static void main(String [] args)
{
int [] num = new int[3];
System.out.print("Enter three numbers: ");
for(int i = 0; i < num.length; i++)
num[i] = Console.readInt(); // read in each number
System.out.println(); // print a new line
// Print each number twice (separated by a dash)
for(int i = 0; i < 3; i++)
System.out.println(num[i] + "-" + num[i]);
}
}
|
A sample program run would look like
Enter three numbers: 9 3 4 9-9-9 3-3-3 4-4-4
public class Arrayiere
{
public static void main(String [] args)
{
int [] num = new int[5];
System.out.print("Enter five numbers: ");
for(int i = 0; i < num.length; i++)
num[i] = Console.readInt(); // read in each number
System.out.println(); // print a new line
// Print the array starting at the back
for(int i = num.length - 1; i >= 0; i--)
System.out.print(num[i] + " ");
}
}
|
The above program prints in reverse each element separated by a space. Adapt the program so that each number appears on a separate line.
A sample program run would look like
Enter five numbers: 19 3 4 7 4 4 7 4 3 19
public class ArraySum
{
public static void main(String [] args)
{
int [] num = new int[6];
System.out.print("Enter six numbers: ");
for(int i = 0; i < num.length; i++)
num[i] = Console.readInt(); // read in each number
// calculate the sum of the all the elements
int sum = 0;
for(int i = 0; i < num.length; i++)
sum = sum + num[i];
System.out.println("The sum of all the numbers is " + sum);
}
}
|
Adapt the program so that it prints out the sum of floating point numbers. You will have to change the declarations of the array num and of sum from int to double. To read in a double, use the readDouble() method of Console.
A sample program run would look like
Enter six numbers: 19.6 3.2 4 7.0 4 5 The sum of all the numbers is 42.8
public class GetArray
{
// the read() method returns an array of integers
int [] read()
{
int len; // number of elements
// ask the user for a valid length ... keep looping til done
do {
len = Console.readInt("How many numbers (1-20)?\n");
} while(len < 1 || len > 20) ;
int [] num = new int[len]; // Declare an array of len elements
// Now get the required numbers
System.out.print("Enter " + num.length + " numbers: ");
for(int i = 0; i < num.length; i++)
num[i] = Console.readInt();
System.out.println();
return num; // return the array
}
}
|
This method can now be used by a different class (in a different file). For example:
public class PrintArray
{
public static void main(String [] args)
{
// Create a GetArray object ...
GetArray getArray = new GetArray();
// now use the read method to get our desired array
int [] num = getArray.read();
// Now print out the array
for(int i = 0; i < num.length; i++)
System.out.println(num[i] + " ");
System.out.println();
}
}
|
Extend the program so that it prints out a histogram of all the numbers entered. i.e. for each number entered the corresponding number of asterisks is printed. a sample run might be
How many numbers (1-20)? 6 Enter 6 numbers: 2 5 1 7 0 3 ** ***** * ******* ***Hint: a nested for loop is needed that might look something like
for(i = 0; i < num.length; i++)
{
// print out the appropriate number of asterisks
for(j = 0; j < num[i]; j++)
System.out.print("*");
System.out.println(); // start a new line
}
public class EvenCount
{
public static void main(String [] args)
{
// Create a GetArray object ...
GetArray getArray = new GetArray();
// now use the read method to get our desired array
int [] num = getArray.read();
System.out.println();
// Now we've got the array, check each element to see
// is it even or not.
int count = 0;
for(int i = 0; i < num.length; i++) // scan all the elements
if(num[i] % 2 == 0) // is this element even ...
count++; // ... yes, increase the count
System.out.println("There are " + count + " even elements");
}
}
|
GetArray.java is available if required.
Adapt the program to count how many of the numbers are greater than 10. A sample run might be
How many numbers (1-20)? 6 Enter 6 numbers: 20 5 11 7 0 13 There are 3 numbers greater than 10
Note that this is a very common task for computers to perform. If a stockbroker has a list of 1000 prices, he might want to find the highest price. Humans can scan through a list of numbers, and concentrate on the largest. They try to remember only the largest number they have seen. The following (fairly standard) algorithm assumes that the first number is the maximum, and then scans through the remaining elements. If any is larger than the current maximum, then make that the new maximum.
public class MaxArray
{
public static void main(String [] args)
{
// Create a GetArray object ...
GetArray getArray = new GetArray();
// now use the read method to get our desired array
int [] num = getArray.read();
// Now we've got the array, find the max element
int max = num[0];
for(int i = 0; i < num.length; i++) // scan all the elements
if(num[i] > max) // is this element greater than max ...
max = num[i]; // ... yes, assign max to this element
System.out.println("Max element is " + max);
}
}
|
GetArray.java is available if required.
Adapt the program so that it finds the smallest element in the array. A sample run might be
How many numbers (1-20)? 6 Enter 6 numbers: 20 5 11 7 10 13 The smallest number is 5
// Find the index of the first element greater than 10
public class Index
{
public static void main(String [] args)
{
// Create a GetArray object ... and read in the array
int [] num = new GetArray().read();
int i;
boolean found = false; // assume not found
for(i = 0; i < num.length; i++) // scan all elements
if(num[i] > 10) // is this element greater than 10 ...
{
found = true;
break; // ... yes, leave the for loop
}
if(found)
System.out.println("The number with index " + i + " is first greater than 10");
else
System.out.println("No number is greater than 10");
}
}
|
GetArray.java is available if required.
Write a program that finds the index of the smallest element in the array. A sample run might be
How many numbers (1-20)? 6 Enter 6 numbers: 20 7 11 5 10 13 The number with index 3 is the smallest numberRemember that the first element of an array is zero, so the fourth element has index 3.
How many numbers (1-20)? 6 Enter 6 numbers: 20 5 11 7 10 13 Numbers less than 10 are at indices: 1 3
public class MakeOdd
{
public static void main(String [] args)
{
// Create a GetArray object ... and read in the array
int [] num = new GetArray().read();
// Now we've got the array, find the odd numbers
for(int i = 0; i < num.length; i++)
if(num[i] % 2 == 0) // is this element even ...
num[i] = num[i] / 2; // ... yes, divide by 2
// finally print out the array
System.out.print("The modified array is ");
for(int i = 0; i < num.length; i++)
System.out.print(num[i] + " ");
}
}
|
GetArray.java is available if required.
Every even number is divided by two. If however, the number is divisible by 4, then it will still be even when divided by 2.
Adapt the program so that it keeps dividing the number until it finds an odd number.
Hint: You want to keep dividing by two while the number is even. However be careful of zero values. A sample run might be
How many numbers (1-20)? 6 Enter 6 numbers: 20 5 11 7 10 13 The modified array is 5 5 11 7 5 13You should think about this program and write down the modifications before you submit the program.
How many numbers (1-20)? 6 Enter 6 numbers: 20 5 11 7 10 13 The modified array is 20 0 11 7 10 13Note that the smallest element, the 5, has become 0.
// This program efficiently counts the different digits that are entered
public class Count
{
public static void main(String [] args)
{
int [] count = new int[10];
int digit;
int i;
for(i = 0; i < 10; i++)
count[i] = 0; // set all counts to zero.
// Keep asking the user to enter digits
System.out.print("Enter digits (0 to 9)? (use -1 to stop): ");
do {
digit = Console.readInt();
if(digit >= 0 && digit < 10)
count[digit]++; // increase count for that digit
} while(digit != -1) ;// ... keep looping til done
// now print out the number of digits
System.out.println();
System.out.println("Digit\tNumber"); // \t is the TAB character
for(i = 0; i < 10; i++)
System.out.println(i + "\t" + count[i]);
}
}
|
Adapt the program so that it doesn't print out any number which doesn't occur (i.e. that has a zero count).
Enter digits (0 to 9)? (use -1 to stop): 2 2 9 2 2 7 -1 Digit Count 2 4 7 1 9 1I.e. the user entered four 2s, one 7 and one 9.