/* */ import java.util.*; public class Miscellaneous { public static void main(String[] args) { test1( ); getWordsTest( ); System.out.println( absValue1(2)); System.out.println( absValue1(-2)); System.out.println( absValue2(2)); System.out.println( absValue2(-2)); test2(); test3(); } public static int absValue1( int x ) { if ( x < 0 ) return -x; else return x; } public static int absValue2( int x ) { return (x < 0 ? -x : x); } public static void test2( ) { double x = 0, y = 1; double max = (x > y) ? x : y ; String s = "hello"; double z = 32.4; double x2 = s.equals("zero") ? 0.0 : 3*(z + 13.2); } public static void test3( ) { 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 ); } }