import java.util.ArrayList; import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; /** * This class will translate words and phrases from one language to * another (e.g., English to Pirate). * * @author Dave Reed * @version 2/9/05 */ public class Translator { private ArrayList fromLanguage; // words in the original language private ArrayList toLanguage; // corresponding words in other language /** * Constructs a translator with vocabulary read in from a file. * @param filename the file that contains vocabulary words, one per line */ public Translator(String filename) { fromLanguage = new ArrayList(); toLanguage = new ArrayList(); try { Scanner infile = new Scanner(new File(filename)); while (infile.hasNextLine()) { String line = infile.nextLine(); int divider = line.indexOf("|"); fromLanguage.add(line.substring(0, divider)); toLanguage.add(line.substring(divider+1, line.length())); } } catch (FileNotFoundException exception) { System.out.println("NO SUCH FILE FOUND"); } } /** * Translates a word or phrase, replacing words from one language (fromLanguage) * to another (toLanguage). * @param str the word or phrase to be translated * @returns a copy of str with words translated */ public String translate(String str) { for (int i = 0; i < fromLanguage.size(); i++) { str = str.replaceAll("\\b"+fromLanguage.get(i)+"\\b", toLanguage.get(i)); } return str; } }