/* * Snippets for Chapt 24 */ import java.util.*; public class Chapt24Snippets { public static void main(String[] args) { test1( ); getWordsTest( ); test2(); } public static void test2( ) { ArrayList a = new ArrayList(); a.add( new String( "Bob" ) ); // [Bob] a.add( new String( "Carol" ) ); // [Bob, Carol] a.add( 1, new String( "Ted" ) ); // now [Bob, Ted, Carol] System.out.println( a.size( ) ); // should be 3 // String x = a.get( 2 ); // illegal: cannot convert Object to String String y = (String) a.get( 2 ); // okay: returns "Carol" System.out.println( y ); a.clear( ); // clear it out System.out.println( a.size( ) ); // should be 0 } public static void test1( ) { char[ ] c = { 'H', 'e', 'l', 'l', 'o' }; String s = ""; for ( int i = 0; i < c.length; i++ ) { s += c[i]; System.out.println( s ); } StringBuffer b = new StringBuffer( ); b.append( 99.5 ); b.append( '%' ); b.append( "pure" ); System.out.println( b ); } public static void getWordsTest( ) { String s1 = "Do you wake up in the morning feeling sleepy and grumpy?"; System.out.println ( "[" + getWords( s1 ) + "]" ); String s2 = "Then, you must be Snow White."; System.out.println ( "[" + getWords( s2 ) + "]" ); } /** Removes punctuation, maps to lower case, and returns a * string with the remaining words. * @param s The input string. * @return A string containing just the words in lower case. */ public static String getWords( String s ) { String[ ] words = s.split( "[ ,.?]+"); StringBuffer buffer = new StringBuffer( ); for ( int i = 0; i < words.length; i++ ) { buffer.append( words[i].toLowerCase( ) ); if ( i < words.length-1 ) buffer.append( " " ); } return String.valueOf( buffer ); } }