Professional Documents
Culture Documents
Computer Programming - Week 5
Computer Programming - Week 5
Syntax:
Types of Java Decision Control Structures: if ([expression]){
1. If [statement or block of code];
2. If-else }
3. If-else-if or
4. Switch if ([expression]) [statement];
1
Example:
The program prints a message if the final grade of a student exceeds 75%:
Syntax:
public class PassFail1{ if ([expression]){
public static void main (String[] args) [statement1/codeblock1];
{
}
int grade = 85;
else {
if (grade >= 75){ [statement2/codeblock2];
System.out.println("Congratulations!"); }
System.out.println("You Passed!");
or
}
if ([expression]) [statement1];
}
} else [statement2];
Example:
The program prints a message if the final grade of a student exceeds 75%, else
it would print another message if the student fails to exceed 75%:
2
Example:
The program prints two separate messages if the final grade of a student
exceeds 85% and 75%, else it would print another message if the student
fails to exceed 75%:
public class PassFail3{ Syntax:
public static void main (String[] args)
switch ([switch expression])
{
{
int grade = 95; case 1:
if (grade >= 85){
[statement1];
System.out.println("Congratulations!");
System.out.println("You Excelled!"); case 2:
} [statement2];
else if (grade >= 75 ){ case n:
System.out.println("Good!");
System.out.println("You Passed!"); [statement];
} default:
else{ ..
System.out.println("Sorry!");
System.out.println("You failed!");
}
}
} What are the differences between switch statements and if statements?
}
Example:
The program prints a message for each corresponding grade rating based
on given grade ranges:
public class PassFail4{
public static void main (String[] args){
char rating;
switch (rating) {
case 'S':
System.out.println("Excellent!");
break;
case 'A':
System.out.println("Good!");
break;
case 'B':
System.out.println("Study Harder!");
break;
default:
System.out.println("You failed!");
break;
}
}
}
3
Computer Programming (JAVA) – Week 5 Page 1 of 2
References
Deitel, H., & Deitel, P. (2004). Java: How to program (early objects). Prentice Hall.
Lambert, K., Osborne, M. (2011). Fundamentals of Java. Cengage Learning Asia Pte Ltd.