Java01 Seq288 Day 3
Java01 Seq288 Day 3
action ;
JAVA PROGRAMMING I
15TH JULY, 2011 DAY 3
For example, a Bicycle class could allow the brakes to decrease the bicycle's speed only if the bicycle is already in motion. One possible implementation of the applyBrakes() method could be as follows: public void applyBrakes(){ if (isMoving){ // the "if" clause: bicycle must be moving. isMoving here is a boolean currentSpeed--; // the "then" clause: decrease current speed } }
If this test evaluates to false (meaning that the bicycle is not in motion), control jumps to the end of the if- then statement. In addition, the opening and closing braces are optional, provided that the "then" clause contains only one statement: void applyBrakes(){ if (isMoving) currentSpeed--; // same as above, but without braces }
Deciding when to omit the braces is a matter of personal taste, but you should note that omitting them can make the code more brittle. If a second statement is later added to the "then" clause, a common mistake would be forgetting to add the newly required braces. The compiler cannot catch this sort of error; you'll just get the wrong results.
JAVA PROGRAMMING I
15TH JULY, 2011 DAY 3
public class ControlFlow{ /** * @param args */ public static void main(String[] args) {
String ageString = JOptionPane.showInputDialog("Please enter your first name"); int age = Integer.parseInt(ageString); if(age >= 18){ JOptionPane.showMessageDialog(null, "You can go to the movies all by yourself!"); } if(age < 18){ JOptionPane.showMessageDialog(null, "Sorry. You need a chaperone."); } } } The if-then-else Statement
The if- then-else statement provides a secondary path of execution when an "if" clause evaluates to false. statement;
3
JAVA PROGRAMMING I
15TH JULY, 2011 DAY 3
} else { statement ; } You could use an i f- then-else statement in the applyBrakes() method to take some action if the brakes are applied when the bicycle is not in motion. In this case, the action is to simply print an error message stating that the bicycle has already stopped. void applyBrakes(){ if (isMoving) { currentSpeed--; } else { System.err.println("The bicycle has already stopped!"); } } Example import javax.swing.JOptionPane; public class ControlFlow { /** * @param args */ public static void main(String[] args) {
JAVA PROGRAMMING I
15TH JULY, 2011 DAY 3
String ageString = JOptionPane.showInputDialog("Please enter your first name"); int age = Integer.parseInt(ageString); if(age >= 18){ JOptionPane.showMessageDialog(null, "You can go to the movies."); } else{ JOptionPane.showMessageDialog(null, "Parental guidance is adviced."); } } } The for statement The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows: for (expression1; expression2; expression3) { statement(s) } expression1 initializes the loop control variable and is executed once, as the loop begins expression2 is the loop continuation condition, where the counter is evaluated after each iteration
JAVA PROGRAMMING I
15TH JULY, 2011 DAY 3
expression3 increments the control variable. This may increment or decrement the counter variable Note that a counter controlled structure requires: The name of a control variable initial value of the control variable increment or decrement by which the control variable is modified each time through the loop for(int i = 0; i < 15; i++){ //statements } The following program uses the general form of the for statement to print the numbers 1 through 10 to standard output: class ForDemo { public static void main(String[] args){ for(int i=1; i<=10; i++){ System.out.println("i is: " + i); } } } The output of this program is:
6
JAVA PROGRAMMING I
15TH JULY, 2011 DAY 3
i is: 1 i is: 2 i is: 3 i is: 4 i is: 5 i is: 6 i is: 7 i is: 8 i is: 9 i is: 10 Notice how the code declares a variable within the initialization expression. The scope of this variable extends from its declaration to the end of the block governed by the for statement, so it can be used in the termination and increment expressions as well. If the variable that controls a for statement is not needed outside of the loop, it's best to declare the variable in the initialization expression. The names i , j , and k are often used to control for loops; declaring them within the initialization expression limits their life span and reduces errors. The three expressions of the for loop are optional; an infinite loop can be created as follows: for ( ; ; ) { // infinite loop // your code goes here
JAVA PROGRAMMING I
15TH JULY, 2011 DAY 3
} The for statement also has another form designed for iteration through Collections and arrays. This will be discussed later under Arrays. The while and do-while Statements The while statement continually executes a block of statements while a particular condition is true. Its syntax can be expressed as: while (expression) { // statement(s) } The while statement evaluates expression, which must return a boolean value. If the expression evaluates to true, the while statement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false. Using the while statement to print the values from 1 through 10 can be accomplished as in the following program: class WhileDemo { public static void main(String[] args){ int count = 1; while (count <= 10) { System.out.println("Count is: " + count); count++;
8
JAVA PROGRAMMING I
15TH JULY, 2011 DAY 3
} } } You can implement an infinite loop using the while statement as follows: while(true){ // your code goes here } The Java programming language also provides a do-while statement, which can be expressed as follows: do { statement(s) } while (expression); The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once, as shown in the following program: class DoWhileDemo { public static void main(String[] args){ int count = 1; do {
9
JAVA PROGRAMMING I
15TH JULY, 2011 DAY 3
System.out.println("Count is: " + count); count++; } while (count <= 10); } } Summary of Control Flow Statements The if-then statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code only if a particular test evaluates to true. The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to false. The while and do-while statements continually execute a block of statements while a particular condition is true. The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once. Exercises 1. Express the following if- then statements by using if-then-else structure if(a < b) x = y ; if(a > b ) {} if(a == b) x = z ;
2. Write a program that assigns a grade based on the value of a test score:
10
JAVA PROGRAMMING I
15TH JULY, 2011 DAY 3
90 <= score 80 <= score < 90 70 <= score < 80 60 <= score < 70 Score < 60
A B C D F
3. Use the above control statements as appropriate to print out all prime numbers between 1 and 100 inclusive. Hint: use the % operator
4. Write a simple guessing game that works as follows: Ask a user to guess the lucky number for the day between some range, say 100 and 500. Use nested loops to check whether the number entered in correct. The lucky number should be programmed in the code.
11