Monday 15 June 2015

Flow Control 5: Branching Statements - break

public class BreakDemo {
        /* break statements are used to terminate
         * switch blocks, for, while and do-while loops.
         */
        public static void main(String[] args) {
                // Variable declarations;
                int i = 2;
                int searchFor = 3;
                int[] numbers = {0,1,2,3,4,5};
                boolean foundIt = false;

                // Simple switch block with break statements.
                switch (i) {
                        case 0:
                                System.out.println("A = " + (i++));
                                break;
                        case 1:
                                System.out.println("A = " + (i++));
                                break;
                        case 2:
                                System.out.println("A = " + (i++));
                                break;
                        default:
                                System.out.println("Resetting A.");
                                i = 0;
                                break;
                }

                // Simple for loop with a break statement.
                for (i = 0; i < numbers.length; i++) {
                        if (numbers[i] == searchFor) {
                                foundIt = true;
                                break;
                        }
                }
                if (foundIt) {
                        System.out.println(searchFor + " is at index " + i);
                } else {
                        System.out.println(searchFor + " could not be found.");
                }

                // Simple while loop with a break statement.
                while(foundIt) {
                        System.out.println("i = " + (i++));
                        if (i == 100) {
                                System.out.println("i = " + i);
                                i = 0;
                                break;
                        }
                }

                // Simple do-while loop with a break statement.
                do {
                        if (i == 100) {
                                System.out.println("i = " + i);
                                break;
                        }
                        System.out.println("i = " + (i++));
                } while (foundIt);

                /* Since there is no code included in either
                 * of the while or do-while loops to make foundIt
                 * false. Both loops should effectively be infinite.
                 * However using if-then with break gives us another
                 * opportunity to test for a condition that should
                 * terminate the loop.
                 */
        }
}

No comments:

Post a Comment

Translate