/* T01n14.java -- Given a message typed by the user, find all periods and * replace them with exclamation points, and find all exclamation points * and add another exclamation point after each one. For example: * Hey! Slow down. ---> Hey!! Slow down! * * This is the third of three examples that do this same task, but in * different ways: * * T01n12.java -- Using Strings, build the new string a character at a time * T01n13.java -- Still using only Strings, use substring() to build the * new string in chunks (uses fewer concatenations). * T01n14.java -- Convert the input into a StringBuilder object and * manipulate it directly. */ import java.util.*; public class T01n14 { public static void main (String [] args) { String message; // User's boring/exciting message Scanner keyboard = new Scanner (System.in); // Input is from keyboard System.out.print("Please type in a message : "); message = keyboard.nextLine(); message = addExcitement(message); System.out.println("\nThank you. If you had been more excited, " + "you'd have typed your message\nlike this:\n\t" + message); } /* This version of addExcitement converts the user's String into * a StringBuilder object so that we can change the message * directly instead of building new strings via concatenation. */ private static String addExcitement (String original) { StringBuilder excited; // Reference to built-up resulting message int currentChar = 0, // *Index* of current punctuation character firstPeriod, // closest subsequent (.) w.r.t. current loc. firstExclamation, // closest subsequent (!) w.r.t. current loc. earliest; // location of closest subsequent (.) or (!) excited = new StringBuilder (original); while (true) { // Starting where we left off, find the next // occurrences of (.) and (!). This is more // complex than necessary; StringBuilder does // have an indexOf() method that would be a better // choice. This is how you'd have had to do it // with StringBuffer, prior to Java 1.4. firstPeriod = excited.toString().indexOf('.',currentChar); firstExclamation = excited.toString().indexOf('!',currentChar); // If we can't find any more of either, leave loop if (firstPeriod < 0 && firstExclamation < 0) { break; } else { // At least one . or ! exists in the remainder of // the user's message. Find the location of the // closest one. if (firstPeriod >=0 && firstExclamation >= 0) { earliest = Math.min(firstPeriod,firstExclamation); } else if (firstPeriod >=0 && firstExclamation < 0) { earliest = firstPeriod; } else { earliest = firstExclamation; } // Add excitement by converting the characters if (excited.charAt(earliest) == '.') { excited.setCharAt(earliest,'!'); // replace . with ! currentChar = earliest + 1; } else { excited.insert(earliest,'!'); // add second ! currentChar = earliest + 2; // move beyond both !'s } } } return excited.toString(); // we need to return a String object } }