非左递归产生式 语义规则
L -> E | L.val = E.val |
E ->TE' | E'.inh = T.val ; E.val = E'.syn; |
E' -> +TE'1 | E'1.inh = E'.inh +T.val E'.syn = E'1.syn |
E' -> -TE'1 | E'1.inh = E'.inh -T.val E'.syn = E'1.syn |
E' ->ε | |
T -> FT' | T'.inh = F.val T.val = T'.syn |
T' ->*FT'1 | T'1.inh = T'.inh * F.val T'.syn = T'1.syn |
T' ->/FT'1 | T'1.inh = T'.inh / F.val T'.syn = T'1.syn |
T' ->ε | |
F ->(E) | F.val = E.val |
F->digit | F.val = get.num |
源代码:
import java.io.*;
public class Calculator
{
private String inexpr;
private int cur;
int L()
{
return E();
}
int E() // E -> TE''
{
int inh,val;
inh = T();
val = E1(inh);
return val;
}
int E1(int inh) // E1 -> +TE1
{
int fval,syn;
char op = inexpr.charAt(cur);
if(op == '+')
{
cur++;
fval = T();
inh = inh + fval;
syn = E1(inh);
}
else if(op == '-')
{
cur++;
fval = T();
inh = inh - fval;
syn = E1(inh);
}
else syn = inh;
return syn;
}
int F()
{
int val = 0;
char digit = inexpr.charAt(cur);
//cur ++;
if(digit >= '0' && digit <= '9')
{
while(digit >= '0' && digit <= '9')
{
val = val*10 + digit - '0';
// digit = inexpr.charAt(cur);
cur ++;
digit = inexpr.charAt(cur);
}
}
else if(digit == '(')
{
cur++;
int x = E();
cur++;
return x;
}
else
System.out.println("error");
return val;
}
int T1(int inh) //T1->*FT1
{
int fval, syn;
char op = inexpr.charAt(cur);
if (op == '*')
{
cur ++;
fval = F();
inh = inh * fval;
syn = T1(inh);
}
else if(op == '/')
{
cur++;
fval = F();
inh = inh/fval;
syn = T1(inh);
}
else syn = inh;
return syn;
}
int T() // T -> FT''
{
int inh, val;
inh = F();
val = T1(inh);
return val;
}
int compute(String expr)
{
inexpr = expr + "$";
cur = 0;
return L();
}
public static void main(String[] args) throws IOException
{
BufferedReader in = new BufferedReader(new FileReader("D://Calculator.in"));
Calculator cal = new Calculator();
String st = in.readLine();
//String st = "(15+3)*2";
while (st.compareTo("#") != 0)
{
System.out.println(cal.compute(st));
st = in.readLine();
//st = "#";
}
}
}
测试数据:
1
478+522
(478+522)*10
1/2-1
1+2*3
(1-2)/3
(1+2)*(3+4)/(5-6)
((1+2)*1+2)*(1+(3-2/5))
#
测试结果:
1
1000
10000
-1
7
0
-21
20