/* Copyright 2005 Daniel Cer (daniel.cer@cs.colorado.edu) This work is licensed under the Creative Commons Attribution-NonCommercial- ShareAlike License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/2.5/ or send a letter to Creative Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105, USA. */ import java.io.FileReader; import java.io.BufferedReader; import java.util.ArrayList; public class LinearSearch { static public void main(String[] args) throws Exception { if (args.length != 2) { System.err.println( "Usage:\n\tjava LinearSearch (search term) (file with list of terms)"); System.exit(-1); } String term = args[0]; String fileName = args[1]; ArrayList entries = new ArrayList(); // read in the entries BufferedReader reader = new BufferedReader(new FileReader(fileName)); for (String inLine;(inLine=reader.readLine())!=null; ) entries.add(inLine); reader.close(); // find the first match / check to see if there are any matches int lineNumber; if ((lineNumber = entries.indexOf(term)+1) == 0) { System.err.println("Search term not found."); System.exit(-2); } // locate all of the remaining matches for (int removed=0; lineNumber!=0; lineNumber=entries.indexOf(term)+1){ System.out.printf("found match on line: %d\n", lineNumber+removed); entries.remove(lineNumber-1); removed++; // slow for large lists } } }