Conditional Loops Lesson Slides

Conditional Loops
Objectives:
Understand the semantics and learn the Java syntax pertaining to
Conditional Loops
Be able to create a conditional loop based on problem
circumstances
The Conditional Loop
A conditional loop repeats a block
of code indefinitely until some
condition is no longer met
8-3
The conditional Loop
while (test condition is true)
{
statement1;
statement2;
...
statement;
}
The body of
the loop
condition is any
boolean expression,
like an if
• The code inside will NEVER be executed unless the test
condition is true.
• This implies, it will never STOP executing as long as the test
condition is true
The conditional Loop (cont’d)
Example: Continually ask the user for a number until it is in range
import java.util.Scanner;
static Scanner input = new Scanner(System.in);
public static void main(String [] args)
{
int num = 0;
//Keep asking for input until the number is between 1 and 10
while (num < 1 || num > 10)
{
System.out.println(“Enter a number between 1 and 10, inclusive”);
num = Integer.parseInt(input.nextLine());
}
System.out.println(“w00t, you entered a valid number”);
}
Exiting a Loop
Early
private static void main(String[] args)
{
Rectangle[] obstacles = new Rectangle[3];
obstacles[0] = new Rectangle(0,0,50,100);
obstacles[1] = new Rectangle(10,90,50,80);
obstacles[2] = new Rectangle(200,10,100,30);
Rectangle player = new Rectangle(10,10,40,100);
int obsIndex = 0;
while(obsIndex < 3)
{
if (BoxBox(player,obstacles[obsIndex]) == true)
{
//obsIndex will hold the index of the
//obstacle that collided
break;
}
obsIndex++;
}
 Sometimes it may be necessary
to exit a loop early and go to the
rest of the code
 You can do this by using the
keyword break
 Example: A program that does
box-to-box collision between a
player and three obstacle
rectangles. It stops as soon as it
finds one, to not waste CPU
//If obsIndex is 3, it fully looped without colliding
if (obsIndex < 3)
{
System.out.println(“Collision found at: “ + obsIndex);
}
}
private boolean BoxBox(Rectangle box1, Rectangle box2)
{
if (box1.x + box1.width < box2.x ||
box1.x > box2.x + box2.width ||
box1.y + box1.height < box2.y ||
box1.y > box2.y + box2.height)
{
return false;
}
return true;
}