Tutorial:BeanShell/7 Loops
Java has very flexible three looping mechanisms. You can use one of the following three loops:
- while Loop
- do...while Loop
- for Loop
The "while" loop
One other point is that the code to be executed if the conditions are met. That means that if you want to loop the next five lines with a 'while' loop, you must put a set number of spaces at the beginning of each of the next five lines.
<jc lang="bsh"> x=0; while( x < 20 ){
print("value of x : " + x ); x++; }
</jc>
The "for" loop
The loop based on "for" is also very popular. Let us print values from 0 to 10 in a for loop:
<jc lang="bsh"> x=10; for(x = 10; x < 20; x++){
print("value of x : " + x ); }
</jc>
One can also break this loop if a condition is met:
<jc lang="bsh"> x=0; for(x=10; x < 20; x++){
if (x==13) break; break the loop here print("value of x : " + x ); }
</jc>
You can also use the continue statement if you want to skip some iteration, without exiting the loop:
<jc lang="bsh"> x=10; for(x = 10; x < 20; x++){
if (x==13) continue; do not print x=13 print("value of x : " + x ); }
</jc>