// WordsBetter.java (c) 2004 Kari Laitinen // http://www.naturalprogramming.com // 2004-10-10 File created. // 2004-12-19 Last modification. // This program is an enhanced version of the program // Words.java in Chapter 6. This program works more like // the corresponding programs in my C++ and C# books. import java.util.* ; import java.util.regex.* ; class WordsBetter { public static void main( String[] not_in_use ) { Scanner keyboard = new Scanner( System.in ) ; System.out.print( "\n This program separates the words of a" + "\n sentence and prints them in wide form." + "\n Type in a sentence.\n\n " ) ; // The Pattern.DOTALL flag specifies that also line-termination // characters are matched by the regular expression "." Pattern match_all_characters = Pattern.compile( ".", Pattern.DOTALL ) ; String character_in_sentence = keyboard.findInLine( match_all_characters ) ; System.out.print( "\n " ) ; while ( character_in_sentence.charAt( 0 ) != '\r' ) { if ( character_in_sentence.charAt( 0 ) == ' ' ) { System.out.print( "\n " ) ; } else { System.out.print( " " + character_in_sentence ) ; } character_in_sentence = keyboard.findInLine( match_all_characters ) ; } } } /* Multiline comment: findInLine() method ignores delimiters. The pattern specified by string "." means that any character is accepted "[\\d\\s]" would mean any digit or any whitespace character. */