// Whitaker Brand // CSE142 // Winter 17 // TA: Eddie Smintina // Section: CB // This program is an example of a fence-post loop; fence-post loops // are useful when you are trying to do a repeated task where part of // the task happens one extra time. public class FencePostExample { public static void main(String[] args) { printSeparated("CSE142"); } // accepts a String parameter, and prints the word separated by spaces // "CSE142" // "C-S-E-1-4-2" // - - - - - public static void printSeparated(String word) { // This fencepost solution pulls the first "post" // out of the loop. Pulling the last "post" out // is just as good, and it is typical to choose // whichever is easier System.out.print(word.charAt(0)); for (int i = 1; i < word.length(); i++) { char letter = word.charAt(i); System.out.print("-" + letter); // Note the difference between declaring a String and a char: // char b = 'b'; // String bee = "b"; } System.out.println(); // This is a BAD example of a "fencepost" solution, where // an if/else is used inside the loop to figure out if // the first/last execution of the loop is happening, // and only put a "post" during that loop execution. for (int i = 0; i < word.length(); i++) { char letter = word.charAt(i); if (i == word.length() - 1) { System.out.print(letter); } else { System.out.print(letter + "-"); } } } }