Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* SearchCmd.java
- Written by Rune Hansen
- Updated by Alexandre Buisse <abui@itu.dk>
- */
- import java.io.*;
- class HTMLlist
- {
- String str;
- HTMLlist next;
- HTMLlist (String s, HTMLlist n) //Constructor
- {
- str = s;
- next = n;
- }
- }
- class Searcher
- {
- public static boolean exists (HTMLlist l, String word) //Static method. So it starts with the first node and cheks if the String word (the word we're searching for is in the list
- {
- //The l-Node is the CurrentNode
- while (l != null)
- {
- if (l.str.equals (word)) //finds the word
- {
- return true;
- }
- l = l.next; //if it didn't find the word it goes to the next item
- }
- return false; //if the word was not in the list
- }
- public static HTMLlist readHtmlList (String filename) throws IOException
- { //This method builds the list from the beginning because the words have to be in the same order as they are in the file
- String name;
- HTMLlist start, current, tmp; //start=firstNode. Three fields?
- // Open the file given as argument
- BufferedReader infile = new BufferedReader(new FileReader(filename));
- name = infile.readLine(); //So first we read the first node(word in the list) from the file
- start = new HTMLlist (name, null); //creates the firstNode by using it's name for the item and puts its nextreference to null
- current = start; //sets the item to be the first
- name = infile.readLine(); // Read the next line of the (txt)file
- while (name != null) { // Exit if it is null. goes to close
- tmp = new HTMLlist(name,null); //creates a new node with the word from the file in it and puts it on the tmpfield
- current.next = tmp; //the old next.field points to the new item
- current = tmp; // Update the linked list???
- name = infile.readLine(); // Read the next line
- }
- infile.close(); // Close the file
- return start;
- }
- }
- public class SearchCmd
- {
- public static void main (String[] args) throws IOException
- {
- String name;
- // Check that a filename has been given as argument
- if (args.length != 1)
- {
- System.out.println("Usage: java SearchCmd <datafile>");
- System.exit(1);
- }
- // Read the file and create the linked list
- HTMLlist l = Searcher.readHtmlList (args[0]);
- // Ask for a word to search
- BufferedReader inuser =
- new BufferedReader (new InputStreamReader (System.in));
- System.out.println ("Hit return to exit.");
- boolean quit = false;
- while (!quit) {
- System.out.print ("Search for: ");
- name = inuser.readLine(); // Read a line from the terminal
- if (name == null || name.length() == 0)
- {
- quit = true;
- }
- else if (Searcher.exists (l, name)) {
- System.out.println ("The word \""+name+"\" has been found.");
- }
- else
- {
- System.out.println ("The word \""+name+"\" has NOT been found.");
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement