Version 2 (modified by 6 years ago) (diff) | ,
---|
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:
- Create a new folder in your Java Projects folder named Conditional Example
- Create a new file (New->File)
- Cut and paste this program into the file.
public class ConditionalExample { public static void main(String args[]) { int rangeInInches; rangeInInches = 10; if (rangeInInches < 20) { System.out.println("stop motors so we don't crash!"); } else { System.out.println("full speed ahead!"); } } }
- Save the program as ConditionalExample.java (notice how the name of the file must match the name of the class)
Running the program
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.
- Restart the program using the restart tool
- Change the values stored in the variable rangeInInches to 25 and observe the flow of the program.
Extra Credit
Java allows you to have multiple conditionals using the syntax:
if (<condition 1>) { // do this if condition 1 is true // also do this if condition 1 is true } else if (<condition 2>) { // do this if condition 1 was not true but condition 2 is true } else { // do this if neither condition 1 nor condition 2 were true }
You can have as many else if clauses as you wish.
- Try adding an else if clause to the sample program.
Some things to note:
- The conditions are always placed within parentheses
- The conditions are logic statements that must evaluate to true or false (e.g. (a < 10))
- The conditions are evaluated in order and the first condition that matches is executed, the rest are skipped
- The else if and else clauses are optional