350 likes | 359 Views
Learn how to use if, else, and switch statements to control the execution of code in Java. Explore examples and syntax for single-selection, double-selection, nested if statements, and switch statements.
E N D
Topic 03Control Statements Programming II/A CMC2522 / CIM2561 Bavy Li
Background • Our problem-solving solutions so far have the straight-line property public class DisplayForecast // main(): application entry point public static void main(String[] args) { System.out.print("I think there is a world"); System.out.print(" market for maybe five "); System.out.println("computers. “); System.out.print(" Thomas Watson, IBM, “); System.out.println("1943.“); } }
Background • For general problem solving we need more capabilities • The ability to control which statements are executed • The ability to control how often a statement is executed • Java provides the if and switch conditional constructs to control whether a statement list is executed • Java provides the while and for iteration constructs to control whether a statement list is executed
Selection Statements • Using if and if...else • Single-selection structure • Double-selection structure • Nested if Statements • Multiple-selection structure • Using switch Statements • Conditional Operator
Basic if statement • Syntax if (Expression) { Action; } • If the Expression is true then execute Action • Action is either a single statement or a group of statements (in block) within braces Expression true false Action
Example – Basic if statement if (value < 0) { value = -value; }
Self-Test Question System.out.print("Enter an integer number: "); int value1 = Integer.parseInt(stdin.readLine()); System.out.print("Enter another integer number: "); int value2 = Integer.parseInt(stdin.readLine()); // rearrange numbers if necessary if (value2 < value1) { // values are not in sorted order int rememberValue1 = value1; value1 = value2; value2 = rememberValue1; } // display values System.out.println("The numbers in sorted order are " + value1 + " and then " + value2); What happens if the user enters 11 and 28? What happens if the user enters 11 and 4?
Expression false true Action1 Action2 The if-else statement • Syntax if(Expression) { Action1} else { Action2 } • If Expression is true then executeAction1otherwise execute Action2
Example – Finding maximum values System.out.print("Enter an integer number: "); int value1 = Integer.parseInt(stdin.readLine()); System.out.print("Enter another integer number: "); int value2 = Integer.parseInt(stdin.readLine()); int maximum; if (value1 < value2) { // is value2 larger? maximum = value2; // yes: value2 is larger } else { // (value1 >= value2) maximum = value1; // no: value2 is not larger } System.out.println("The maximum of " + value1 + " and " + value2 + " is " + maximum);
Multiple Alternative if Statements if (score >= 90) grade = ‘A’; else if (score >= 80) grade = ‘B’; else if (score >= 70) grade = ‘C’; else if (score >= 60) grade = ‘D’; else grade = ‘F’; if (score >= 90) grade = ‘A’; else if (score >= 80) grade = ‘B’; else if (score >= 70) grade = ‘C’; else if (score >= 60) grade = ‘D’; else grade = ‘F’;
Example – Checking vowels switch (ch) { case 'a': case 'A': case 'e': case 'E': case 'i': case 'I': case 'o': case 'O': case 'u': case 'U': System.out.println("vowel“); break; default: System.out.println("not a vowel“); } The break causes an exiting of the switch Handles all of the other cases
Example – Simple calculations System.out.print("Enter a number: "); int n1 = Integer.parseInt(stdin.readLine()); System.out.print("Enter another number: "); int n2 = Integer.parseInt(stdin.readLine()); System.out.print("Enter desired operator: "); char operator =stdin.readLine().charAt(0); switch (operator) { case '+' :System.out.println(n1 + n2); break; case '-' :System.out.println(n1 - n2); break; case '*' :System.out.println(n1 * n2); break; case '/' :System.out.println(n1 / n2); break; default: System.out.println(“Illegal request“); }
switch Statement Rules • The switch-expression must yield a value of char, byte, short, or int type and must always be enclosed in parentheses • The value1, ..., and valueN must have the same data type as the value of the switch-expression • The case statements are executed in sequential order • The keyword break is optional to use at the end of each case in order to terminate from the switch statement. But if the break statement is not present, the next case statement will be executed
Conditional Operator (Boolean Expression) ? exp1 : exp2
Examples – Conditional Operator if (x > 0) y = 1 else y = -1; is equivalent to y = (x > 0) ? 1 : -1; if (num % 2 == 0) System.out.println(num + “is even”); else System.out.println(num + “is odd”); is equivalent to System.out.println( (num % 2 == 0)? num + “is even” : num + “is odd”);
Repetition Statements • Looping: while, do-while and for • DO it if and only if condition is true • DO it at least one before testing the condition • DO it repeatedly until the counter is over • Nested loops • Using break and continue
Example – while Loop Flow Chart int i = 0; while (i < 100) { System.out.println( "Welcome to Java!"); i++; }
The do-while statement • Syntax do { Action } while(Expression) • Semantics • Execute Action • If Expression is true then execute Action again • Repeat this process until Expression evaluates to false Action true Expression false
Nested loops int m = 2; int n = 3; for (int i = 0; i < n; ++i) { System.out.println("i is " + i); for (int j = 0; j < m; ++j) { System.out.println(" j is " + j); } }
i is 0 j is 0 j is 1 i is 1 j is 0 j is 1 i is 2 j is 0 j is 1 Nested loops int m = 2; int n = 3; for (int i = 0; i < n; ++i) { System.out.println("i is " + i); for (int j = 0; j < m; ++j) { System.out.println(" j is " + j); } }
break Statement vs. continue Statement • The break Statement • It causes an immediate exit from the structures of (while, for, do-while), then execution continues with the next statement • The continue Statement • It skips the remaining statement in the body of the structures of (while, for, do-while), and proceeds with the next iteration of the loop
Using break and continue Discussion on: • Example 3.5 : TestBreak.java • Testing a break Statement • Example 3.6 : TestContinue.java • Testing a continue Statement
Summary • Control Statements • Selection Statements • if, if…else, nested if • switch • conditional operator • Repetition Statements • while, do…while, for • nested loops • break and continue