CS102 Spring
2008
Lab # 4
Recognizing Simple Languages using Grammars and Recursion
In this laboratory exercise you will write a program that implements and tests two simple language recognizer methods from Chapter 6 of the text: isId( ) and isAnBn( ). The main() method, constructor, and test methods for this lab have been provided for you. You need only implement the recursive methods and helper methods. The algorithm for isId( ) appears on page 301 of the text, and isAnBn( ) appears on page 304.
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main();
}
/** Creates a new instance of Main */
public Main() {
this.runIsIdTests();
this.runIsAnBnTests();
}
/**
* Runs tests for isId()
*/
private void runIsIdTests() {
String[] goodIds = {
"public", "static", "void", "main", "Main", "String",
"a12345", "b_$", "__valid$$", "MAXNODES_"
};
String[] badIds = {
"1var", "(parenID)", "%1", "42", "count#", "w's", "|abs|",
"<letter>", "<digit>", "/tag"
};
System.out.println("\nTesting valid Java Identifiers:");
for (String w : goodIds) {
if (this.isId(w)) {
System.out.println("PASSED: " +
"isId( " + w + " ) was true");
}
else {
System.out.println("FAILED: " +
"isId( " + w + " ) was false");
}
}
System.out.println("\nTesting invalid Java Identifiers:");
for (String w : badIds) {
if (!this.isId(w)) {
System.out.println("PASSED: " +
"isId( " + w + " ) was false");
}
else {
System.out.println("FAILED: " +
"isId( " + w + " ) was true");
}
}
}
/**
* Runs tests for isAnBn()
*/
private void runIsAnBnTests() {
String[] ofFormAnBn = {
"", "AB", "AABB", "AAABBB", "AAAABBBB", "AAAAABBBBB"
};
String[] notOfFormAnBn = {
"A", "B", "AA", "BB", "ABB", "AAB", "ABAB",
"BABA", "AABBAABB", "ABC"
};
System.out.println("\nTesting valid strings of form A^nB^n:");
for (String w : ofFormAnBn) {
if (this.isAnBn(w)) {
System.out.println("PASSED: " +
"isAnBn( " + w + " ) was true");
}
else {
System.out.println("FAILED: " +
"isAnBn( " + w + " ) was false");
}
}
System.out.println("\nTesting invalid strings of form A^nB^n:");
for (String w : notOfFormAnBn) {
if (!this.isAnBn(w)) {
System.out.println("PASSED: " +
"isAnBn( " + w + " ) was false");
}
else {
System.out.println("FAILED: " +
"isAnBn( " + w + " ) was true");
}
}
}
/**
* Returns true if w is a legal java identifier;
* otherwise returns false.
*/
public boolean isId(String w) {
// implement this method }
/**
* Determines whether given character is a letter.
* (helper method for isId)
*/
private boolean isLetter(char c) {
// implement this method }
/**
* Determines whether given character is a digit.
* (helper method for isId)
*/
private boolean isDigit(char c) {
// implement this method }
/**
* Returns true if w is of the form A^nB^n;
* otherwise returns false.
*/
public boolean isAnBn(String w) {
// implement this method
}
From a terminal window, type the following commands:
cd cd cs102submit102 Lab4