If-statements & Indefinite Loops CSE 115 Spring 2006
Download
Report
Transcript If-statements & Indefinite Loops CSE 115 Spring 2006
If-statements &
Indefinite Loops
CSE 115
Spring 2006
April 24, 26, & 28 2006
Selection
Choice in a program.
We’ve seen polymorphism already as a
mechanism for a way for a program to
behave differently under different
conditions.
There is another construct for selection
built into Java: if-statements.
If-statements
Syntax
if (booleanExpression) {
//code executed if boolean
//Expression is true
}
If-else statements
if (booleanExpression) {
//code executed if boolean
//Expression is true
}
else {
//code executed if boolean
//Expression is false
}
If-else statements (more
than two choices)
if (booleanExpression1) {
//code executed if boolean
//Expression1 is true
}
else if (booleanExpression2) {
//code executed if boolean
//Expression2 is true
}
else {
//code executed if neither boolean
//Expression1 or booleanExpression2 is
//true
}
Loops
(Iteration/Repetition)
The ability to do a task repeatedly.
The functionality of repetition is most
often implemented in programming
languages using loops.
Indefinite Loop
There are two types of indefinite loops
built into Java, the while-loop and the dowhile-loop. An indefinite loop is normally
used when you do not know how many
times you want a specific task to be
performed.
Entry vs. Exit Test Loop
A “while-loop” is also characterized as an
entry-test loop (like the for-loop). That is,
a condition about whether the loop
should continue is tested before actually
doing the work of the loop.
A “do-while-loop” is an exit-test loop.
That is, the work of the loop is done
before the condition is tested about
whether the loop should continue.
Syntax of while-loop
while (booleanExpression)
{
//loop body
}
Essentially, keep looping until the
condition is false.
Syntax of do-while-loop
Do {
//loop body
} while (booleanExpression);
Essentially, do it once and then keep
looping until the condition is false.
The equals method
The == operator does not always give us
the desired results when comparing two
objects (non-primitives).
We need to use the equals method to
obtain information about object equality.
All classes inherit this method from
java.lang.Object, but need to override it
to perform as appropriate.
The toString method
Another method inherited from
java.lang.Object that should be
overridden to perform appropriately for
each object.
This method gives a String
representation of an object that can be
printed out to the console using
System.out.println statements.