/* * ====================================================================== * DemoBranching.java: Demo features of branching constructs.... * * Written By: Mark Austin August 2006 * ====================================================================== */ public class DemoBranching { // Constructor method. public DemoBranching() {}; // main method : this is where the program execution begins. public static void main ( String [] args ) { int i = 2, j = 3, k = 3; System.out.printf("Starting variables: i = %2d\n", i ); System.out.printf(" j = %2d\n", j ); System.out.printf(" k = %2d\n", k ); // Part 1: Demonstrate basic if() statement if ( i%2 == 0 ) System.out.println("Part 1: Variable i is EVEN\n"); if ( i%2 == 1 ) System.out.println("Part 1: Variable i is ODD\n"); // Part 2: Demonstrate basic if() then else statement. // The two examples in Part 1 can be combined into a // single if-else statement. if ( j%2 == 0 ) System.out.println("Part 2: Variable j is EVEN\n"); else System.out.println("Part 2: Variable j is ODD\n"); // Part 3: Here is another if-else branching construct System.out.println("Part 3: i = " + i); if (i == 0) { System.out.println("Part 3: In block 1!"); } else { System.out.println("Part 3: In block 2!"); } // Part 4: Demonstrate use of else-if() clause .... int testscore = 78; String grade; if (testscore >= 90) { grade = "A+"; } else if (testscore >= 85) { grade = "A "; } else if (testscore >= 80) { grade = "A-"; } else if (testscore >= 75) { grade = "B+"; } else if (testscore >= 70) { grade = "B "; } else if (testscore >= 65) { grade = "B-"; } else if (testscore >= 60) { grade = "C+"; } else if (testscore >= 55) { grade = "C "; } else if (testscore >= 50) { grade = "C-"; } else grade = "D"; System.out.println("Part 4: Grade = " + grade); // Part 5: Branching construct with more complicated conditional // expression.... i = 0; j = 1; k = 3; System.out.println("Part 5.1: i = " + i + " j = " + j + " k = " + k); if (i == 0 && j <= 1 && (k == 3 || k == 4) ) { System.out.println("Part 5.1: In block 1!"); } else { System.out.println("Part 5.1: In block 2!"); } System.out.println("Note: (i == 0) evaluates to " + (i==0) ); System.out.println(" (j <= 4) evaluates to " + (j<=4) ); System.out.println(" (k == 3 || k == 4) evaluates to " + (k == 3 || k == 4)); // Now let's change the values of i and k ... i = 3; k = 5; System.out.println(""); System.out.println("Part 5.2: i = " + i + " j = " + j + " k = " + k); if (i == 0 && j <= 1 && (k == 3 || k == 4) ) { System.out.println("Part 5.2: In block 1!"); } else { System.out.println("Part 5.2: In block 2!"); } System.out.println("Note: (i == 0) evaluates to " + (i==0) ); System.out.println(" (j <= 4) evaluates to " + (j<=4) ); System.out.println(" (k == 3 || k == 4) evaluates to " + (k == 3 || k == 4)); } }