Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Programming Problem 15.14 IdentifierIndex with LabRat Write a program that reads a Java source file and produces an index of all identifiers in the file.
Programming Problem 15.14 IdentifierIndex with LabRat
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.
Use the following class as your main class:
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 Setidents = index.getIdentifiers(); for (String ident : idents) { Set lines = index.getLines(ident); System.out.println(ident + ": " + lines); } } }
Complete the following class in your solution:
/** 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 SetgetIdentifiers() { . . . } /** 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 getLines(String identifier) { . . . } }
Use the following class as your tester class:
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 Setidents = index.getIdentifiers(); String last = ""; for (String s : idents) { last = s; } System.out.println(last); // The last identifier System.out.println("Expected: void"); Set 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: []"); } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started