// This program demonstrates several new concepts, including: // - String methods (charAt, length, etc.) // - fencepost loops // - String cumulative "sum" // - while loops // - sentinel loops 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(); printPowers(2, 100); printPowers(10, 100000); printPowers2(2, 100); printPowers2(10, 100000); System.out.println(); Scanner console = new Scanner(System.in); System.out.println(sumAll(console)); } // 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)); } // Print out the powers of base up to the first power of base that is // greater than last // e.g. 2, 10 -> 2, 4, 8, 16, 32, 64, 128 // // int base - the base of the powers to be printed // int last - the number after which to stop printing powers public static void printPowers(int base, int last) { // indefinite loop int power = base; System.out.print(power); while (power < last) { System.out.print(", "); power *= base; System.out.print(power); } System.out.println(); } // Read in integers from the user until a -1 is typed, // then return the sum of all numbers typed (not including // the -1). // // Scanner console - the Scanner to use for input public static int sumAll(Scanner console) { int total = 0; System.out.print("Enter an integer (-1 to stop): "); int number = console.nextInt(); while (number != -1) { total += number; System.out.print("Enter an integer (-1 to stop): "); number = console.nextInt(); } return total; } }