Download public class WhileLoop1

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
CSCI1402 Introductory Java Programming
Week 7 Lecture2
Control Structures (cont)
Repetition
Sometimes we may want our program to repeat the same instruction more than
once. The following example displays a single asterisk on a new line 10 times.
public class Asterisks {
public static void main(String args[])
{
System.out.println("*"); // display an asterisk
System.out.println("*"); // display an asterisk
System.out.println("*"); // display an asterisk
System.out.println("*"); // display an asterisk
System.out.println("*"); // display an asterisk
System.out.println("*"); // display an asterisk
System.out.println("*"); // display an asterisk
System.out.println("*"); // display an asterisk
System.out.println("*"); // display an asterisk
System.out.println("*"); // display an asterisk
System.out.println(“Asterisks displayed above”);
} // end main method
} // end class
Java, like most programming languages, provides much more efficient
mechanisms to implement repetition in a program. We often refer to these
mechanisms as loops.
We have already used a for loop to process data stored in an array
Java provides 3 kinds of loops:
 the for loop
 the while loop
 the do-while loop
The next example uses a while loop to display the 10 asterisks
Page 1 of 11
1
CSCI1402 Introductory Java Programming
Week 7 Lecture2
public class Asterisks {
public static void main(String args[])
{
int counter; // declare counter
counter = 0; // initialise counter to 0
while(counter < 10) //test the condition- is counter less than 10?
{
System.out.println("*"); // display an asterisk
counter++; // increment counter
} //go and test condition again
System.out.println(“Asterisks displayed above”);
} // end main method
} // end class




The variable counter is given an initial value of 0.
The while statement tests to see what value is currently being stored in
counter and compares this value with the test condition.
In this example, the value of counter is tested to see if it is less than 10.
If it is less than 10, then the instructions in the body of the while loop
will be executed.
The body is contained between the braces:
{
System.out.println("*"); // display an asterisk
counter++; // increment counter
} //go and test condition again
In this example, the body has two instructions
1. Display an asterisk on a new line
2. Add 1 to the value of counter

When the body has been executed, the program will return to the while
statement again to re-test the condition. It will continue to “loop” in this way
until counter is no longer less than 10, i.e. the test condition is no longer true

The program will now continue to execute the instructions after the loop. In
this example, it will display “Asterisks displayed above”
Page 2 of 11
2
CSCI1402 Introductory Java Programming
Week 7 Lecture2
The relational operators
>
is greater than
<
is less than
>= is greater than or equal to
<=
is less than or equal to
==
is equal to
!=
is not equal to
The result of a comparison is a boolean value, either true or false. For example:
boolean result;
result = (x==y);
“result is assigned the boolean value which results from comparing x with y”
result will have the value true if x is the same as y, otherwise result will have
the value false
What would be the outcome of the following programs?
int counter;
counter = 0;
while(counter < 5)
{
System.out.print("*");
counter++;
}
System.out.println(“Asterisks displayed above”);
int counter;
counter = 1;
while(counter <=10)
{
System.out.print("*");
counter++;
}
System.out.println(“Asterisks displayed above”);
Page 3 of 11
3
CSCI1402 Introductory Java Programming
Week 7 Lecture2
int counter;
counter = 10;
while(counter < 10)
{
System.out.print("*");
counter++;
}
System.out.println(“Asterisks displayed above”);
int counter;
counter = 0;
while(counter <= 10)
{
System.out.print("*");
}
System.out.println(“Asterisks displayed above”);
int counter;
counter = 0;
while(counter >10)
{
System.out.print("*");
counter++;
}
System.out.println(“Asterisks displayed above”);
int counter;
counter = 0;
while(counter ==10)
{
System.out.print("*");
counter++;
}
System.out.println(“Asterisks displayed above”);
Page 4 of 11
4
CSCI1402 Introductory Java Programming
Week 7 Lecture2
int counter;
counter = 10;
while(counter >0)
{
System.out.print("*");
counter--;
}
System.out.println(“Asterisks displayed above”);
int counter;
counter = 10;
while(counter >0)
{
System.out.print("*");
counter++;
}
System.out.println(“Asterisks displayed above”);
Page 5 of 11
5
CSCI1402 Introductory Java Programming
Week 7 Lecture2
The while loop can be used to process an array. The following loops achieve the
same result:
char a = {‘C’,’S’,’C’,’I’,’1’,’4’,’0’,’2’};
‘C’
‘S’
‘C’
0
1
2
‘I’
‘1’
‘4’
‘0’
‘2’
3
4
5
6
7
(a) Using a for loop
for (int index=0; index<a.length; index++)
{
System.out.print(a[index]);
}
(b) Using a while loop
int index;
index = 0;
while(index < a.length)
{
System.out.print( a[index]);
index++;
}
In the brackets after the for loop, we can declare the control variable, set the
control variable to the initial start value, test to see if the control variable has
reached the termination condition and increment or decrement the control
variable
In the brackets after the while loop, we are only able to test to see if the
control variable has reached the termination condition. Declaration and
initialisation of the control variable must be done before the loop and
increment/ decrement of the control variable must be done inside the loop body
Why bother with a while loop? Because you don’t always know when you write
the program how many times the loop is to be executed, this is often dependent
upon some user input. For example:
char continue = ‘y’;
while (continue !=’n’)
{
/* play a game of some kind */
System.out.println(”Do you want another go? (y/n) “);
continue = KeyBoardIn.readChar();
}
Page 6 of 11
6
CSCI1402 Introductory Java Programming
Week 7 Lecture2
do-while loop
counter = 1; //initialise counter to 1
do
{
System.out.print("!");
counter++; // increment counter
} while(counter <= 5); //test condition

An important point about for loops and while loops is that the conditional
expression is always tested at the beginning of the loop i.e. before each
iteration. This means that the code inside the loop may not be executed
at all if the condition is false to begin with. For example:
int count, x = 0;
for(count = 10; count < 5; count++)
{
x+=count; // add the value of count to x . Equivalent to x = x+ count;
}



The do-while loop, however, checks its condition at the end of the loop.
This means that it will always execute at least once
So the condition can be dependant upon some data which is unknown at the
start of the loop but is acquired from executing the body of the loop
Page 7 of 11
7
CSCI1402 Introductory Java Programming
Week 7 Lecture2
Example - Using a do-while loop we can make the program loop until the user
guesses the correct letter
char answer = 'K';
char ch;
do
{
System.out.println("I'm thinking of a letter between A and Z");
System.out.print("Can you guess it: ");
ch = KeyBoardIn.readChar(); // get the users guess
if(ch < answer)
{
System.out.println("**...Sorry, you're too low**");
}
else if(ch > answer)
{
System.out.println("**...Sorry, you're too high**");
}
else
{
System.out.println("**Right**");
}
}while (answer !=ch); /*check to see if guess matches answer. If not, do body of
loop again */
Page 8 of 11
8
CSCI1402 Introductory Java Programming
Week 7 Lecture2
The program below uses a while loop to display the value of x successively from 1
to 5
public class DisplayX{
public static void main(String args[])
{
int x; // declare x
x = 1; // initialise x to 1
while(x<=5) // test the condition
{
System.out.println(“x = “ + x); //display the value of x
x++; // increment x
} //go and test condition again
} // end main method
} // end class
This could have been written using a do-while loop
public class DisplayX
{
public static void main(String args[])
{
int x; // declare x
x = 1; // initialise x to 0
do
{
System.out.println(“Value of x = “ + x);
x++; // increment x
} while(x<=5); // test the condition
}
}
This could have been written using a for loop
public class DisplayX
{
public static void main(String args[])
{
int x;
for(x=1; x<=5; x++)
{
System.out.println(“Value of x = “ + x);
} //increment x then go and test condition again
} // end main method
} // end class
Page 9 of 11
9
CSCI1402 Introductory Java Programming
Week 7 Lecture2
Declaring the control variable inside a for loop

Often the variable that controls a for loop is used only to control the loop
and is not used elsewhere. In this case, it is possible to declare the loop
variable inside the initialisation part of the loop. The following loop
displays the value of variable counter at each repetition
for (int counter = 1; counter <=10; counter++)
{
System.out.println(counter);
}

But it is important to remember that the scope of the variable counter
ends when the for loop does so the program cannot refer to it outside of
the for loop. The following would not compile:
for (int counter = 1; counter <=10; counter++)
{
System.out.println(counter);
}
System.out.println(counter);
The Scope and Lifetime of Variables
Java allows variables to be declared within any block . The block defines the
scope of the variable. The scope of a variable is its lifetime so normally a
variable is not accessible outside of its scope. The scope of a variable
declared in main() is the whole of the program. Consider the following:
public static void main(String args[]){
int counter;
for(counter = 0; counter < 10; counter++)
{
System.out.println(“Count = “ + counter);
{
for(int counter = 10; counter > 0; counter--) //cannot declare counter again
{
System.out.println(“This will not compile”);
}
}
Page 10 of 11
10
CSCI1402 Introductory Java Programming
Week 7 Lecture2
Incomplete for loops

It is possible to leave any or all of the initialisation, condition or iteration
parts of the loop blank. Look at the following:
int i;
for (i = 1; i <=10;)
{
System.out.print(i + " ");
i++;
}

Here the loop control variable is incremented inside the body of the for
loop. What would happen if the i++ was omitted?
The infinite loop


Occasionally, certain kinds of systems programs require an infinite loop.
This is often when a system is to continue to execute a particular block of
code until interrupted by a user or a physical device e.g. a printer
requiring attention
Infinite for loops can be used for other purposes but are considered bad
practice. For example:
char ch;
for (;;)
{
ch = KeyBoardIn.readChar();
System.out.println(ch);
if (ch == 'q') break;
}

This will continue to prompt for, read and display characters until the
user enters ‘q’

A while or do-while loop would be a better choice:
Page 11 of 11
11