Matt Gerrans
Posts: 1153
Nickname: matt
Registered: Feb, 2002
|
|
Re: simple help needed
|
Posted: Jan 29, 2003 8:33 PM
|
|
/**
* Shortest.java
*
* Simple demo of sorting Strings by length.
*
* Copyright 2003, Matt Gerrans.
*
* If you find this code useful, please buy a pizza for the next skinny
* homeless person you see.
*
* Turning in this code as homework is a violation of ethical principals,
* and punishable by severe penalties, even if you change the variable
* names.
*/
import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Shortest
{
public static void main(String[] args) throws IOException
{
System.out.println( "Enter some gibberish, followed by Ctrl-Z." );
BufferedReader input = new BufferedReader( new InputStreamReader(System.in) );
// Load the strings into a list, since we don't know ahead of time how
// many there might be:
List stringList = new ArrayList();
// Read each line, then extract words from each line with the
// StringTokenizer and add them to the list:
String line = input.readLine();
while( line != null )
{
StringTokenizer st = new StringTokenizer( line );
while(st.hasMoreTokens())
stringList.add( st.nextToken() );
line = input.readLine();
}
if( stringList.size() > 0 )
{
Object [] stringArray = stringList.toArray();
// Create a custom Comparator to sort by the length of the strings.
Arrays.sort( stringArray, new Comparator()
{
public int compare( Object a, Object b )
{
return ((String)a).length() - ((String)b).length();
}
} );
System.out.println( "Words, sorted by length: " );
for( int i = 0; i < stringArray.length; i++ )
System.out.println( stringArray[i] );
}
else
System.out.println( "Try typing in some words next time." );
}
}
|
|