Write KeywordCounter, which reads Java source code from the input and counts its keywords (class, int, if, while, …; include true, false and null).
- Put the keywords in a
HashSet: testing whether a word is a keyword is then onecontainscall. - Words inside
//comments,/* … */comments, string literals and character literals must not be counted: first replace those parts by a space. - Count each keyword in a
TreeMap, so that the report is alphabetical, and collect the other identifiers in a set to know how many different ones there are.
For the input
public class Demo {
// this comment mentions while and for, which must not be counted
private static final int LIMIT = 10;
public static void main(String[] args) {
int total = 0;
for (int i = 0; i < LIMIT; i++) {
if (i % 2 == 0) {
total += i; /* else, return and class inside a comment */
} else {
continue;
}
}
String text = "if this were code, new and try would count";
char quote = '"';
while (total > 0) {
total = total / 2;
}
System.out.println(text + total + quote);
}
}
the program prints
Keywords: 17 (13 different)
char: 1
class: 1
continue: 1
else: 1
final: 1
for: 1
if: 1
int: 3
private: 1
public: 2
static: 2
void: 1
while: 1
Different identifiers: 12