Write a program which takes a Java program as input and outputs the program, num
ID: 3817428 • Letter: W
Question
Write a program which takes a Java program as input and outputs the program, numbering the lines, followed by an alphabetical cross-reference listing of all user identifiers; that is, a user identifier is followed by the numbers of all lines in which the identifier appears. If an identifier appears more than once in a given line, the line number must be repeated the number of times it appears.
The cross-reference listing must not contain Java reserved words, words within character strings or words within comments.
Explanation / Answer
Hi,
Please find below the java code-
import java.io.*;
import java.util.Scanner;
public class HelloWorld
{
public static void main(String[] args) {
System.out.println("Enter the path of source file: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String pathToFile = null;
try {
pathToFile = br.readLine();
File f = new File(pathToFile);
Scanner s = new Scanner(f);
s.useDelimiter("[^A-Za-z0-9_]+");
while (s.hasNext()) {
String identifier = s.next();
if (identifier.matches("(abstract|assert|boolean|break|byte|case|catch|char|class|const|continue|default|do|double|else|extends|final|finally|float|for|goto|if|implements|import|instanceof|int|interface|long|native|new|package|private|protected|public|return|short|static|strictfp|super|synchronized|switch|this|throw|throws|transient|try|void|volatile|while|InputStreamReader|BufferedReader|String|Double|boolean|char|byte|short|int|long|float).*")) {
continue;
}
else {
System.out.println(identifier);
}
}
} catch (IOException ioe) {
System.out.println("Unable to locate file. Program will exit. "
+ ioe.toString());
System.exit(0);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.