Re: Write a program that reads a Java source-code file and displays
all the comments.
anon36@yahoo.com wrote:
I am trying to do exercise 17 on page 546 of Bruce Eckel's Thinking In
Java (4th edition):
"Write a program that reads a Java source-code file (you provide the
file name on the command line) and displays all the comments."
This is at the end of a section about regular expressions. We have
just learnt how to use appendReplacement().
Does anyone have a solution to this exercise? or any hints?
The way I would do it would be to create a Reader on the file, read each
character and perform simple lexical analysis there, like so:
boolean inEOLComment = false, inCComment = false, inString = false;
for each character in stream:
if inEOLComment:
print character
if character is newline, inEOLComment = false
else if inCComment:
if character is * and next is /, inCComment = false
else print character
else if inString:
if character is \, skip next character
else if character is ", inString = false
else if character is /:
if next character is /, inEOLComment = true
else if next character is *, inCComment = true
else if character is ", inString = true
else, do nothing
(writing the actual Java code is left as an exercise to the reader)
(I would also like solutions to the following two exercises: write a
program that reads a Java source-code file and displays all the string
literals; and write a program that examines Java source code and
produces all the class names used in a particular program.)
The first should be a trivial modification of the previous code, and the
latter requires some more complex modification. Look up lexical analysis
and parsing for more details.
Note: The code I provided does not provide for preprocessing of Unicode
escapes. If you need to handle that, the easiest way would be to wrap an
input stream.
--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth