forked from SEA-CS-Salinas/stacks-lab-2-JDovalina
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSyntaxChecker.java
More file actions
77 lines (65 loc) · 2.16 KB
/
SyntaxChecker.java
File metadata and controls
77 lines (65 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
//(c) A+ Computer Science
//www.apluscompsci.com
//Name -Jacob Dovalina
import java.util.Stack;
public class SyntaxChecker {
private String exp;
private Stack<Character> symbols;
// Default constructor
public SyntaxChecker() {
this.exp = "";
this.symbols = new Stack<>();
}
// Parameterized constructor
public SyntaxChecker(String s) {
this.exp = s;
this.symbols = new Stack<>();
}
// Method to set a new expression
public void setExpression(String s) {
this.exp = s;
this.symbols.clear(); // Clear the stack for a new expression
}
// Method to check if the expression is balanced
public boolean checkExpression() {
String opening = "{([<";
String closing = "})]>";
for (char ch : exp.toCharArray()) {
if (opening.indexOf(ch) != -1) {
// Push opening symbols onto the stack
symbols.push(ch);
} else if (closing.indexOf(ch) != -1) {
// Check if stack is empty or the top of the stack doesn't match
if (symbols.isEmpty() || closing.indexOf(ch) != opening.indexOf(symbols.pop())) {
return false;
}
}
}
// If the stack is empty, the expression is balanced
return symbols.isEmpty();
}
// toString method to display the result
@Override
public String toString() {
return exp + " is " + (checkExpression() ? "correct." : "incorrect.");
}
// Main method for testing
public static void main(String[] args) {
SyntaxChecker checker = new SyntaxChecker();
// Test cases
String[] testCases = {
"(abc(*def)",
"[{}]",
"[",
"[{<()>}]",
"{<html[value=4]*(12)>{$x}}",
"[one]<two>{three}(four)",
"car(cdr(a)(b)))",
"car(cdr(a)(b))"
};
for (String testCase : testCases) {
checker.setExpression(testCase);
System.out.println(checker);
}
}
}