class Copy {
private GetNext getChar = new GetNext();
private char next;
private String P() {
String res;
scan();
res = E();
if (next != '$') return "ERROR";
else return res + "$";
}
private String E() {
String res;
char save;
res = T();
while (next == '+' || next == '-') {
save = next;
scan();
res = res + save + T();
}
return res;
}
private String T() {
String res;
char save;
res = S();
while (next == '*' || next == '/') {
save = next;
scan();
res = res + save + S();
}
return res;
}
private String S() {
String res;
res = F();
if (next == '^') {
scan();
res = res + "^" + S();
}
return res;
}
private String F() {
String res = "";
if (Character.isLetter(next)) {
res = next + "";
scan();
}
else if (next == '(') {
scan();
res = "(" + E();
if (next == ')') {
res = res + ")";
scan();
}
else {
error(2);
res = "ERROR";
}
}
else {
error(3);
res = "ERROR";
}
return res;
}
private void scan() {
while (Character.isWhitespace(next =
getChar.getNextChar()))
;
}
private void error(int n) {
System.out.println("*** ERROR: " + n);
System.exit(1);
}
public static void main(String[] args) {
Copy copy = new Copy();
String res = copy.P();
System.out.println(res);
}
}
|
class Parens {
private GetNext getChar = new GetNext();
private char next;
private String P() {
String res;
scan();
res = E();
if (next != '$') return "ERROR";
else return res;
}
private String E() {
String res;
char save;
res = T();
while (next == '+' || next == '-') {
save = next;
scan();
res = "(" + res + save + T() + ")";
}
return res;
}
private String T() {
String res;
char save;
res = S();
while (next == '*' || next == '/') {
save = next;
scan();
res = "(" + res + save + S() + ")";
}
return res;
}
private String S() {
String res;
res = F();
if (next == '^') {
scan();
res = "(" + res + "^" + S() + ")";
}
return res;
}
private String F() {
String res = "";
if (Character.isLetter(next)) {
res = next + "";
scan();
}
else if (next == '(') {
scan();
res = E(); // "(" + missing
if (next == ')') {
// res = res + ")"; missing
scan();
}
else {
error(2);
res = "ERROR";
}
}
else {
error(3);
res = "ERROR";
}
return res;
}
private void scan() {
while (Character.isWhitespace(next =
getChar.getNextChar()))
;
}
private void error(int n) {
System.out.println("*** ERROR: " + n);
System.exit(1);
}
public static void main(String[] args) {
Parens parens = new Parens();
String res = parens.P();
System.out.println(res);
}
}
|