// Zorah Fung, CSE 142 // An example of "fencepost" problems public class FencepostFun { public static void main(String[] args) { printLetters("Atmosphere"); // A, t, m, o, s, p, h, e, r, e printLetters2("banana"); // b, a, n, a, n, a printPrimes(50); } // Prints out the letters of the given word with commas in between // NOTE: version 1. Pull out the post first public static void printLetters(String word) { System.out.print(word.charAt(0)); // (post) for (int i = 1; i < word.length(); i++) { System.out.print(", "); // (wire) System.out.print(word.charAt(i)); // (post) } System.out.println(); } // NOTE: version 2. Pull out post at the end public static void printLetters2(String word) { for (int i = 0; i < word.length() - 1; i++) { System.out.print(word.charAt(i)); // (post) System.out.print(", "); // (wire) } System.out.println(word.charAt(word.length() - 1)); } // Prints all prime numbers up to the given max, separated by commas. public static void printPrimes(int max) { if (max > 1) { // post. We have to pull out the post first, since // we don't know what the last prime is System.out.print(2); for (int i = 3; i <= max; i++) { int factors = countFactors(i); if (factors == 2) { System.out.print(", " + i); // wire, post } } System.out.println(); } } // Returns the number of factors of the given integer. // Assumes that n >= 1. public static int countFactors(int n) { int count = 0; for (int i = 1; i <= n; i++) { if (n % i == 0) { count++; } } return count; } }