/* svuk002@ec.auckland.ac.nz * * */ import java.io.*; import java.util.*; public class ReplaceAnswer { private static String fileIn; /* This is the input file */ private static String fileOut; /* This is the output file */ private static boolean overwrite; /* True if we are overwriting fileIn */ private static String[] oldWords; /* Words to be replaced */ private static String[] newWords; /* Replacement words */ public ReplaceAnswer () { /* Begin the main program loop */ mainLoop (); } /* You need to complete this method. * */ private void mainLoop () { try { BufferedReader br = new BufferedReader (new FileReader (fileIn)); BufferedWriter bw = new BufferedWriter (new FileWriter (fileOut)); String currLine; while ((currLine = br.readLine ()) != null) { String newLine = replace (currLine); bw.write (newLine + "\n"); } br.close (); bw.close (); if (overwrite) { File in = new File (fileIn); File out = new File (fileOut); in.delete (); out.renameTo (in); } } catch (FileNotFoundException e) { e.printStackTrace (); } catch (IOException e) { e.printStackTrace (); } } /* You need to complete this method. * */ private String replace (String line) { StringTokenizer st = new StringTokenizer (line); String toRet = ""; while (st.hasMoreTokens ()) toRet += getNewWord (st.nextToken ()) + " "; return toRet; } /* You don't have to modify method below. * It gets the replacement word for the word passed as argument. */ private String getNewWord (String old) { for (int i = oldWords.length - 1; i > -1; i--) if (oldWords[i].equals (old)) return newWords[i]; return old; } /* You don't have to modify the main method */ public static void main (String[] args) { if (checkArgs (args)) new ReplaceAnswer (); else printUsage (); } /* You don't have to modify the method below. * Its purpose is to ``parse'' the command--line arguments * and set appropriate flags. */ public static boolean checkArgs (String[] args) { Vector oldW = new Vector (); Vector newW = new Vector (); try { int currArg = 0; fileIn = args[currArg++]; if (args[currArg].charAt (0) == '-') { if (args[currArg].charAt(1) != 'o') throw new ArrayIndexOutOfBoundsException (); currArg++; fileOut = args[currArg++]; } else { fileOut = fileIn + "temp"; overwrite = true; } for (int i = currArg; i < args.length; i+=2) { oldW.add (args[i]); newW.add (args[i+1]); } oldWords = new String[oldW.size ()]; newWords = new String[newW.size ()]; for (int i = 0; i < newW.size (); i++) { oldWords[i] = (String)oldW.elementAt (i); newWords[i] = (String)newW.elementAt (i); } } catch (ArrayIndexOutOfBoundsException e) { /* Oops... */ return false; } catch (StringIndexOutOfBoundsException e) { /* Oops... */ return false; } return true; } /* You don't have to modify the method below. * It's purpose is to print usage of the program, * in case things go wrong. */ public static void printUsage () { String usage = "Usage: java Replace input_file [-o output_file] oldWord1 " + "newWord1 [oldWord2 newWord2 ...]"; System.out.println (usage); } }