[computer science] c programming

profilesehj
LongWord.java

import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class LongWord { public static void main( String[] args ) { BufferedReader fileIn = null; PrintWriter fileOut = null; String inputLine; String longWord; int lineCount = 0; try { fileIn = new BufferedReader( new FileReader( "cat_wiki.txt" ) ); fileOut = new PrintWriter( new FileWriter( "out.txt" ) ); inputLine = fileIn.readLine( ); while( inputLine != null ) { lineCount++; longWord = getLongestWord( inputLine ); if( longWord.length( ) > 0 ) { fileOut.println( "Line #" + lineCount + ": " + longWord ); } inputLine = fileIn.readLine( ); } fileIn.close( ); fileOut.close( ); } catch( IOException ex ) { System.out.println( ex.getMessage( ) ); ex.printStackTrace( ); } finally { if( fileIn != null ) { try { fileIn.close( ); } catch( IOException ex ) { // Ignore. Errors should be already handled above } } if( fileOut != null ) { fileOut.close( ); } } } public static String getLongestWord( String line ) { String longest = ""; int longestLength = 0; String current = ""; int currentLength = 0; int pos = 0; char ch; while( pos < line.length( ) ) { ch = line.charAt( pos ); if( ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' ) { if( currentLength > longestLength ) { longest = current; longestLength = currentLength; } current = ""; currentLength = 0; } else if( (ch == '\'' || ch == '-') && pos > 0 && Character.isLetter( line.charAt( pos - 1 ) ) && pos < line.length( ) - 1 && Character.isLetter( line.charAt( pos + 1 ) ) ) { current += ch; } else { current += ch; currentLength++; } pos++; } if( currentLength > longestLength ) { longest = current; longestLength = currentLength; } return longest; } }