| 1 | Programs need to be able to react differently to varying data. Conditional statements let us do this. For example, a robot must be able to monitor its sensors to prevent collisions. Consider (and try running) the following program: |
| 2 | |
| 3 | 1. Create a new folder in your Java Projects folder named Conditional Example |
| 4 | 1. Create a new file (New->File) |
| 5 | 1. Cut and paste this program into the file. |
| 6 | {{{ |
| 7 | public class ConditionalExample { |
| 8 | public static void main(String args[]) { |
| 9 | int rangeInInches; |
| 10 | |
| 11 | rangeInInches = 10; |
| 12 | |
| 13 | if (rangeInInches < 20) { |
| 14 | System.out.println("stop motors so we don't crash!"); |
| 15 | } else { |
| 16 | System.out.println("full speed ahead!"); |
| 17 | } |
| 18 | } |
| 19 | } |
| 20 | }}} |
| 21 | 1. Save the program as !ConditionalExample.java (notice how the name of the file must match the name of the class) |
| 22 | |
| 23 | === Running the program |
| 24 | Run the program using the debugger with a breakpoint set on the first executable line (rangeInInches=10); |
| 25 | * Step through the program using the stepover tool and observe the flow of the program. |
| 26 | * Restart the program using the restart tool |
| 27 | * Change the values stored in the variable rangeInInches to 25 and observe the flow of the program. |
| 28 | |
| 29 | === Extra Credit === |
| 30 | Java allows you to have multiple conditionals using the syntax: |
| 31 | {{{ |
| 32 | if (<condition 1>) { |
| 33 | // do this if condition 1 is true |
| 34 | // also do this if condition 1 is true |
| 35 | } else if (<condition 2>) { |
| 36 | // do this if condition 1 was not true but condition 2 is true |
| 37 | } else { |
| 38 | // do this if neither condition 1 nor condition 2 were true |
| 39 | } |
| 40 | }}} |
| 41 | You can have as many ''else if'' clauses as you wish. |
| 42 | |
| 43 | Some things to note: |
| 44 | * The conditions are always placed within parentheses |
| 45 | * The conditions are logic statements that must evaluate to true or false (e.g. (a < 10)) |
| 46 | * The conditions are evaluated in order and the '''first''' condition that matches is executed, the rest are skipped |
| 47 | * The ''else if'' and ''else'' clauses are optional |