// This program demonstrates several new concepts, including: // - String methods (charAt, length, etc.) // - fencepost loops // - while loops // - sentinel loops // - random numbers // - String cumulative "sum" import java.util.*; public class LoopPractice { public static void main(String[] args) { System.out.println(doubleLetters("hello")); System.out.println(doubleLetters("Mississippi")); System.out.println(doubleLetters("abracadabra")); System.out.println(); spellOut("hello"); spellOut("abracadabra"); spellOut("supercalifragilisticexpialidocious"); System.out.println(); spellOutAlt("hello"); spellOutAlt("abracadabra"); spellOutAlt("supercalifragilisticexpialidocious"); System.out.println(); for (int i = 1; i < 5; i++) { rollDice(); System.out.println(); } Scanner console = new Scanner(System.in); System.out.println(concatenateAll(console)); } // Returns a new String with each character from the given String // doubled. // e.g. hello -> hheelllloo // // 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)); } // Simulates rolling a six-sided die repeatedly until a 6 is rolled, // counting how many rolls are made. public static void rollDice() { Random rand = new Random(); int roll = rand.nextInt(6) + 1; int count = 1; while (roll != 6) { System.out.println("You rolled a " + roll); roll = rand.nextInt(6) + 1; count++; } System.out.println("You rolled a 6!"); System.out.println("You won in " + count + " rolls."); } // Reads in a sequence of words from the user until "quit" is typed, // then returns all the typed words (except "quit") concatenated // together. public static String concatenateAll(Scanner console) { String result = ""; System.out.print("Next word (or \"quit\" to end): "); String word = console.next(); while (!word.equals("quit")) { result += word; System.out.print("Next word (or \"quit\" to end): "); word = console.next(); } return result; } }