// Miya Natsuhara // 07-31-2019 // CSE142 // TA: Grace Hopper // This program searches a text file containing information about the top 250 rated // movies on IMDB for movies containing a particular word in the title, then // prints the results to an output file. import java.util.*; import java.io.*; public class ImdbSearch { public static void main(String[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("imdb.txt")); Scanner console = new Scanner(System.in); // NOTE: we did not add this functionality in class, but rather than printing the matched // lines to the console, here we are outputting them to a file named imdb_results.txt. PrintStream output = new PrintStream(new File("imdb_results.txt")); System.out.print("search phrase? "); String searchPhrase = console.nextLine(); String matchedLine = find(input, searchPhrase); // post while (matchedLine.length() > 0) { output.println(highlight(matchedLine, searchPhrase)); // wire matchedLine = find(input, searchPhrase); // post } } // Searches through the passed input file and returns the first line // that contains the given search phrase. // Scanner input: input file to be searched through // String phrase: the phrase to be searched for in the input file public static String find(Scanner input, String phrase) { while (input.hasNextLine()) { String line = input.nextLine(); // effectively checking "containsIgnoreCase" if (line.toLowerCase().contains(phrase.toLowerCase())) { return line; } } // no match is found return ""; } // Highlights (in all caps and surrounded with **) the given search phrase in the // given line and returns the result. // String matchedLine: line of input to be highlighted // String searchPhrase: specific phrase to be highlighted inside the given line public static String highlight(String matchedLine, String searchPhrase) { Scanner lineScan = new Scanner(matchedLine); String result = ""; while (lineScan.hasNext()) { String token = lineScan.next(); if (token.equalsIgnoreCase(searchPhrase)) { // highlighting result += "**" + token.toUpperCase() + "** "; } else { // leave it as it was result += token + " "; } } return result; } }