Saturday 27 June 2015

Flow Control 7: Branching Statements - continue

public class ContinueDemo {
        /* The continue statement works in a similar way
         * to the break statement. It works with for,
         * while and do-while loops and comes in labelled
         * and unlabelled forms.
         *
         * When invoked, continue skips the current iteration
         * of the loop.
         */
        public static void main(String[] args) {
                // Unlabelled example of continue.
                String searchMe = "peter piper picked a peck of pickled peppers.";
                int max = searchMe.length();
                int numPs = 0;

                for (int i = 0; i < max; i++) {
                        if (searchMe.charAt(i) != 'p')
                                continue;

                        numPs++;
                }
                System.out.println("Found " + numPs + " Ps.\n");

                // Labelled example of continue.
                searchMe = "Look for a sub string in me.";
                String substring = "sub";
                boolean foundIt = false;
                max = searchMe.length() - substring.length();

                test:
                        for (int i = 0; i <= max; i++) {
                                int n = substring.length();
                                int j = i;
                                int k = 0;

                                while (n-- != 0) {
                                        if (searchMe.charAt(j++) != searchMe.charAt(k++)) {
                                                continue test;
                                        }
                                }

                                foundIt = true;
                                        break test;
                        }
                        System.out.println(foundIt ? "Fount it" : "Didn't find it");
        }
}

No comments:

Post a Comment

Translate