// This program demonstrates several new concepts, including: // - String methods (charAt, length, etc.) // - fencepost loops // - String cumulative "sum" import java.util.*; public class LoopPractice { public static void main(String[] args) { System.out.println(doubleLetters("abcde")); System.out.println(doubleLetters("Mississippi")); System.out.println(doubleLetters("abracadabra")); System.out.println(); spellOut("hello"); spellOut("CSE142"); spellOut("Happy Birthday"); System.out.println(); spellOutAlt("hello"); spellOutAlt("CSE142"); spellOutAlt("Happy Birthday"); System.out.println(); } // Returns a new String with each character from the given String // doubled. // e.g. hello -> hheelllloo // Note that this is a form of a cumulative sum using Strings! // // String word - the String whose letters should be doubled public static String doubleLetters(String word) { String result = ""; for (int i = 0; i < word.length(); i++) { // String letter = word.substring(i, i + 1); char letter = word.charAt(i); result = result + letter + letter; } return result; } // Prints out the the characters in the given String separated // by dashes. // e.g. hello -> h-e-l-l-o // // String word - the String to print public static void spellOut(String word) { System.out.print(word.charAt(0)); for (int i = 1; i < word.length(); i++) { System.out.print("-" + word.charAt(i)); } System.out.println(); } // Alternate version of spellOut that removes the last instance // of the fencepost instead of the first. // // String word - the String to print public static void spellOutAlt(String word) { for (int i = 0; i < word.length() - 1; i++) { System.out.print(word.charAt(i) + "-"); } System.out.println(word.charAt(word.length() - 1)); } }