Transcript Lecture 10
Common Loop Errors
ITP © Ron Poet
Lecture 10
1
A Semicolon Too Many
What does the following code do?
sum = 0;
for (i = 1; i <= 10; i++);
sum += i;
con.println(“Sum = “ + sum);
It prints 11!
ITP © Ron Poet
Lecture 10
2
Rearranging
There is an extra semi-colon.
The loop has an empty body.
sum = 0;
for (i = 1; i <= 10; i++)
;
sum += i;
con.println(“Sum = “ + sum);
Only the last value of i is added to sum.
ITP © Ron Poet
Lecture 10
3
Loops with Variable Number of
Iterations
ITP © Ron Poet
Lecture 10
4
User Specifies Number of
Iterations
The loops we have seen so far have been simple.
The number of times we go round the loop is written in
the program.
In many loops the number of iterations is not
known until the program runs.
For example, a program to calculate the average of
a series on integers.
We don’t know how many integer there are until the
program runs.
ITP © Ron Poet
Lecture 10
5
User Tells Us First
The easiest solution to this problem is if the
first thing the user tells us is how many
numbers there will be.
We read this into a variable first.
Then we write the loop, using the variable
to decide when to stop.
ITP © Ron Poet
Lecture 10
6
Program Outline
Set total to 0.
Ask user to tell us how many numbers.
Read how many numbers from the user.
Loop this number of times
Read the number
Add to total
Calculate average
ITP © Ron Poet
Lecture 10
7
Java (1)
//Set total to 0.
int total = 0;
//Ask user to tell us how many numbers.
con.print(“How many numbers? “);
//Read how many numbers from the user.
int howMany = con.readInt();
ITP © Ron Poet
Lecture 10
8
Java (2)
//Loop this number of times
for (int i = 0; i < howMany; i++)
{
//Read the number
int number = con.readInt();
//Add to total
total += number;
}
// Calculate Average
double average = (double)total / howMany;
ITP © Ron Poet
Lecture 10
9
User Must Count
This approach is the easiest.
It relies on the user knowing how many
items will follow.
This is potentially error prone.
It is also out of our control.
In many cases the next method is
preferable, even though it is harder to
program.
ITP © Ron Poet
Lecture 10
10
Users Says When He Is Finished
It is easier for the user if he gives us numbers until
he is finished.
He then tells the program that there are no more
numbers.
This is done by choosing a “special” number that
means we are finished.
It cannot be a possible “real” number.
In our example, -1 can be this sentinel value.
Our program must also count the numbers.
ITP © Ron Poet
Lecture 10
11
Program Design
Set total and howMany to 0.
Give user instructions
Loop
Read a number.
If it is the sentinel, exit.
Increment total and count
Calculate average.
ITP © Ron Poet
Lecture 10
12
Java
//Set total and howMany to 0.
int total = 0, howMany = 0;
//Give user instructions
Con.println(“Enter numbers, terminates by –1: “);
ITP © Ron Poet
Lecture 10
13
Java
//Loop
for (;;)
{
//Read a number.
int number = con.readInt();
//If it is the sentinel, exit.
if (number == -1)
break;
//Increment total and count
total += number;
howMany++;
}
//Calculate average.
double average = (double)total / howMany;
ITP © Ron Poet
Lecture 10
14
Easier For The User
This approach is easier for the user.
They do not need to count the numbers in
advance.
It is more robust.
The user cannot say that there are 6 numbers
and then try and enter 7.
The program is not that harder.
ITP © Ron Poet
Lecture 10
15
End Of File Loops
ITP © Ron Poet
Lecture 10
16
Data Files
In many cases data files will contain a series of
similar lines.
Each line should be processed in the same way.
The values in each line will be different.
How do we know when we have read them all?
We could place a sentinel value at the end.
Alternatively, we could let Java tell us when we
have reached the end of the file.
ITP © Ron Poet
Lecture 10
17
EndOfFileException
We keep reading lines until there are no
more lines left to read.
Using a loop.
We will attempt to read past the end of file.
FileIn will throw an EndOfFileException
which we can catch.
This will terminate the loop.
ITP © Ron Poet
Lecture 10
18
Code Overview
try
{
Code that could throw the exception
}
catch (EndOfFileException x)
{
Process the exception.
}
ITP © Ron Poet
Lecture 10
19
The Whole Loop in the Try
The whole loop should be inside the try block.
It will be an infinite loop.
We jump to the catch block when we reach the end
of file.
This terminates the loop because it comes after the
loop.
We don’t need to do anything to process this
exception.
ITP © Ron Poet
Lecture 10
20
Sample File
Just one word per line
one
two
three
Read the word and print on a Console.
ITP © Ron Poet
Lecture 10
21
The Code
import FormatIO.*;
public class Ex1 {
public static void main(String[] args)
{
FileIn fin = new FileIn("test.txt");
Console con= new Console();
try
{
for (;;)
{
String s = fin.readWord();
con.println("[" + s + "]");
}
}
catch (EndOfFileException x) {}
con.println("Finished");
}
}
ITP © Ron Poet
Lecture 10
22