Java Reference
In-Depth Information
sum = 0;
isNegative = false ;
while (console.hasNext() && !isNegative)
{
num = console.nextInt();
if (num < 0)
//if the number is negative, terminate the
//loop after this iteration
{
System.out.println("Negative number found in the data.");
isNegative = true ;
}
else
sum = sum + num;
}
This while loop is supposed to find the sum of a set of positive numbers. If the data set
contains a negative number, the loop terminates with an appropriate error message. This
while loop uses the flag variable isNegative to accomplish the desired result. The variable
isNegative is initialized to false before the while loop. Before adding num to sum ,the
code checks whether num is negative. If num is negative, an error message appears on
the screen and isNegative is set to true . In the next iteration, when the expression in
the while statementisevaluated,itevaluatesto false because !isNegative is false .
(Note that because isNegative is true , !isNegative is false .)
The following while loop is written without using the variable isNegative :
sum = 0;
while (console.hasNext())
{
num = console.nextInt();
if (num < 0)
//if the number is negative, terminate the loop
{
System.out.println("Negative number found in the data.");
break ;
}
sum = sum + num;
}
In this form of the while loop, when a negative number is found, the expression in the
if statement evaluates to true ; after printing an appropriate message, the break state-
ment terminates the loop. (After executing the break statement in a loop, the remaining
statements in the loop are skipped.)
The continue statement is used in while , for , and do ... while structures. When the
continue statement is executed in a loop, it skips the remaining statements in the loop
Search WWH ::




Custom Search