chapter 4.4
TRANSCRIPT
IMPLEMENTING MULTIPLE SELECTIONS
Chapter 4.4:
Multiple Selection (nested if) Syntax:
if (expression1) statement1
elseif (expression2) statement2else statement3
Java code (multiple selection)if (a>=1){
System.out.println ("The number you enter is :" + a); System.out.println ("You enter the positive number");
}else if (a<0){
System.out.println ("The number you enter is :" + a); System.out.println ("You enter the negative number");
}else {
System.out.println ("The number you enter is :" + a); System.out.println ("You enter the zero number");
}
Output
Enter the number : 15The number you enter is :15You enter the positive number
Enter the number : -15The number you enter is :-15You enter the negative number Enter the number : 0The number you enter is :0You enter the zero number
Multiple Selections
Example
The grading scheme for a course is given as below:
Mark Grade
90 - 100 A
80 – 89 B
70 – 79 C
60 – 69 D
0 - 59 F
Read a mark & determine the grade.
Multiple Selectionsif (mark >= 90)
grade = ‘A’;
else if (mark >= 80)
grade = ‘B’;
else if (mark >= 70)
grade = ‘C’;
else if (mark >= 60)
grade = ‘D’;
else
grade = ‘F’;
Equivalent code with series of if statements
if ((mark >= 90) && (mark <=100))
grade = ‘A’;
if ((mark >= 80) && (mark >= 89))
grade = ‘B’;
if ((mark >= 70) && (mark >= 79))
grade = ‘C’;
if ((mark >= 60) && (mark >= 69))
grade = ‘D’;
if ((mark >= 0) && (mark >= 59))
grade = ‘F’;
switch Structures (multiple selection)
Expression is also known as selector.
Value can only be integral.
switch (expression){case value1: statements1
break;case value2: statements2
break; ...case valuen: statementsn
break;default: statements}
If expressionmatches value2,control jumpsto here
switch Structures
The switch Statement Often a break statement is used as the last
statement in each case's statement list
A break statement causes control to transfer to the end of the switch statement
If a break statement is not used, the flow of control will continue into the next case
Control flow of switch statement with and without the break statements
Switch/Break Examples
int m = 2;switch (m){ case 1 : System.out.println(“m=1”); break; case 2 : System.out.println(“m=2”); break; case 3 : System.out.println(“m=3”); break; default: System.out.println(“default”);}
int m = 2;switch (m){ case 1 : System.out.println(“m=1”); break; case 2 : System.out.println(“m=2”); break; case 3 : System.out.println(“m=3”); break; default: System.out.println(“default”);}
Output: m=2
char ch = ‘b’;switch (ch){ case ‘a’ : System.out.println(“ch=a”);
case ‘b’ : System.out.println(“ch=b”);
case ‘c’ : System.out.println(“ch=c”);
default: System.out.println(“default”);}
char ch = ‘b’;switch (ch){ case ‘a’ : System.out.println(“ch=a”);
case ‘b’ : System.out.println(“ch=b”);
case ‘c’ : System.out.println(“ch=c”);
default: System.out.println(“default”);}
Output: ch=b ch=c default