Java: Flow of Control
If statement
The statement inside of an if must return a boolean value
meaning true or false. (Note: C/C++ can return
an integer). Otherwise, it is the same as in C/C++ (if, then,
else if, else)
Example:
if(count < 0)
{ System.out.println("Error!"); }
else if (count > 10)
{ System.out.println("Stop being a hog!");
count = 0; /*take that*/ }
else
{ System.out.println("Great Running!");
count++; }
? operator
This conditional operator can also be used. This is the general
formula:
test ? true_result_return : false_result_return
Here is an example:
int minimum = x < y ? x : y;
Switch
This is the same as in C/C++. Here is an example:
switch (option) {
case 0:
System.out.println("You choose Thresholding");
Threshold(); /*call the treshold method of this class*/
break;
case 1:
System.out.println("You choose Bit-Slicing");
BitSlice(); /*call the Bit-slice method of this class*/
break;
default:
System.out.println("Invalid Choice!");
break;
}
//Threshold() and BitSlice() methods defined below
For loop
Same as in C/C++
Exercise
While loop
Same as in C/C++ except must have boolean test.
Can break out
of loops with break; statement and skip a loop with the
continue; statements.
while (boolean test)
{ statements... }
Exercise
Do loop
Same as in C/C++ except must have boolean test. Can break out
of loops with break; statement and skip a loop with the
continue; statements.
do {
statements.....
} while (boolean test)
Labeled Loops
- break label;
- continue label;
- return expression;
- label: statement;
Here is an example,
loop: while (true) { //This is an infinite loop!
switch(option = in.read()) { //reads in a character
case 0:
Threshold(); //call treshold method
break;
case 1:
BitSlice(); //call bitslice method
break;
default:
System.out.println("Invalid Option!");
break loop; // jumps out of while-loop
}
System.out.println("Type in option choice");
}