Write a program that reads a Java source file and produces an index of all identifiers in the file. For each identifier, print all lines in which it occurs.

Hint: Call in.useDelimiter("[^A-Za-z0-9_]+"). Then each call to next returns a string consisting only of letters, numbers, and underscores.

Complete the following file:

IdentifierIndex.java

/** A class to read in a Java source file and produce an index of all identifiers in the file. */ . . . public class IdentifierIndex { . . . /** Reads all identifiers from the given file @param filename the file name */ public void read(String filename) throws FileNotFoundException { . . . } /** A set of all identifiers that occur in the file, in sorted order. */ public Set<String> getIdentifiers() { . . . } /** Gets all line numbers on which the given identifier occurs. @param identifier an identifier @return all line numbers on which the identifier was found, in increasing order; an empty set (not null) if the identifier was never found */ public Set<Integer> getLines(String identifier) { . . . } }

Use the following files:

IndexDemo.java

import java.io.FileNotFoundException;
import java.util.Set;

/**
   A program to read in a Java source file and
   produce an index of all identifiers in the file.
*/
public class IndexDemo
{  
   public static void main(String[] args)
      throws FileNotFoundException
   {  
      IdentifierIndex index = new IdentifierIndex();
      index.read("IndexDemo.java"); // reads this file
      Set<String> idents = index.getIdentifiers();
      for (String ident : idents)
      {
         Set<Integer> lines = index.getLines(ident);
         System.out.println(ident + ": " + lines);
      }
   }
}

IndexTester.java

import java.io.FileNotFoundException;
import java.util.Iterator;
import java.util.Set;

public class IndexTester
{  
   public static void main(String[] args)
      throws FileNotFoundException
   {  
      IdentifierIndex index = new IdentifierIndex();
      index.read("IndexTester.java"); // reads this file
      Set<String> idents = index.getIdentifiers();
      String last = "";
      for (String s : idents) { last = s; }
      System.out.println(last); // The last identifier
      System.out.println("Expected: void");
      Set<Integer> lines = index.getLines("void");
      System.out.println(lines);
      System.out.println("Expected: [7, 16, 17]");
      System.out.println(index.getLines("f" + "oo"));
      System.out.println("Expected: []");
   }
}