Download THE JAVA BREAK and CONTINUE STATEMENTS

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
THE JAVA BREAK and CONTINUE STATEMENTS
The break statement is used as follows:
Uses of the Java Break Statement
Within a switch statement, to transfer execution to the end of the statement that immediately
follows the switch.
Within a loop, to stop cycling the loop and transfer execution to the statement hat immediately
follows the loop.
The continue statement:
Uses of the Java Continue Statement
Within a loop, to skip the remainder of the loop body and immediately begin executing the next
loop cycle.
Example
This code fragment will calculate the sum of positive integers entered by the user. Negative
integers are ignored and entry of 0 causes the loop to halt.
1
2
3
4
5
6
7
8
9
10
11
12
double item, sum = 0;
Scanner input = new Scanner( System.in );
do
{
System.out.print( "Enter an integer: " );
item = input.nextInt( );
if ( item == 0 )
break;
else if ( item < 0 )
continue;
sum += item;
} while ( true );
The Java Break and Continue Statements
Page 1
Exercises
Take the code given in the example of this topic (page 1) and fashion it into a complete working
Java application. Enter it into jGRASP and save it to a file. Compile it and fix any syntax errors.
Perform the following series of experiments and answer any questions.
1.
In jGRASP’s main window, set a breakpoint at the line shown below. To set the breakpoint,
move the mouse cursor to the gray bar at the left of your code. It will display a red dot .
Click the mouse to set the breakpoint.
item = input.nextInt( );
2.
Start jGRASP’s debugger by clicking the Ladybug button
. Execution will pause at the
line marked by the breakpoint. Notice that program execution halts immediately before the
statement has been executed.
In jGRASP’s Debug pane, what is the value of variable sum?
3.
In jGRASP’s Run I/O pane, enter the value 15 for input. Be sure to press the Enter key.
Step over the program statement by clicking the Step button
.
In jGRASP’s Debug pane, what is the value of variable item?
4.
Repeatedly click the Step button until execution returns to the breakpoint.
Which statements were executed? In jGRASP’s Debug pane, what is the value of variable
sum?
5.
Repeat problem 3, this time entering the value -15 for input.
6.
Repeat problem 4.
7.
Repeat problem 3, this time entering the value 0 for input.
8.
Repeatedly click the Step button until the program ends execution.
Which statements were executed?
The Java Break and Continue Statements
Page 2