| 60 | == Conditionals |
| 61 | 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: |
| 62 | {{{ |
| 63 | public class ConditionalExample { |
| 64 | public static void main(String args[]) { |
| 65 | int rangeInInches; |
| 66 | |
| 67 | rangeInInches = 10; |
| 68 | |
| 69 | if (rangeInInches < 20) { |
| 70 | System.out.println("stop motors so we don't crash!"); |
| 71 | } else { |
| 72 | System.out.println("full speed ahead!"); |
| 73 | } |
| 74 | } |
| 75 | } |
| 76 | }}} |
| 77 | * Save the program as ConditionalExample.java (notice how the name of the file must match the name of the class) |
| 78 | * Run the program using the debugger with a breakpoint set on the first executable line (rangeInInches=10); step through the program using the stepover tool and observe the flow of the program. |
| 79 | * What happens if you change the values stored in the variable rangeInInches to 25? |
| 80 | |
| 81 | == Loops |
| 82 | It's also important for a program to be able to do things repeatedly; for example, the robot must read its sensors repeatedly and react only when certain conditions are met. Consider (and try running) the following program: |
| 83 | {{{ |
| 84 | public class LoopExample { |
| 85 | public static void main(String args[]) { |
| 86 | int counter; |
| 87 | |
| 88 | counter = 1; |
| 89 | while (counter <= 10) { |
| 90 | System.out.println(counter); |
| 91 | counter = counter + 1; |
| 92 | } |
| 93 | } |
| 94 | } |
| 95 | }}} |
| 96 | * Save this program as Loop Example |
| 97 | * Run the program in the debugger with a breakpoint set at the line while (counter <= 10) |
| 98 | * Step through the program a line at a time, observing the program output, variables, and flow of execution |
| 99 | |