資源簡介
一、實驗目的
實現一個遞歸下降語法分析程序,識別用戶輸入的算術表達式。
二、實驗主要內容
1、文法如下:
ETE`
E’+TE’|-TE’|
TFT`
T’*FT’|/FT’|
F(E)|i
2、求取各非終結符的First及Follow集合
3、編程實現下降遞歸分析法,識別從鍵盤輸入的關于整數或浮點數的算術表達式(在此,上述文法中的i代表整數或浮點數)
4、對于語法錯誤,要指出錯誤具體信息。

代碼片段和文件信息
import?java.io.BufferedReader;
import?java.io.IOException;
import?java.io.InputStreamReader;
public?class?Analysis?{
private?String?statement;
private?int?index=0;
private?int?kuohu=0;
public?static?void?main(String?arg[]){
System.out.println(“Please?enter?an?arithmetic?expression?to?analyse!“);
BufferedReader?in=new?BufferedReader(new?InputStreamReader(System.in));
String?expression;
try?{
expression?=?in.readLine()+“#“;
Analysis?test=new?Analysis(expression);
test.show();
}?catch?(IOException?e)?{
//?TODO?Auto-generated?catch?block
System.out.println(“輸入出錯!“);
}
}
public?Analysis(String?expression){
statement=expression;
}
public?void?show(){
try?{
E();
System.out.println(“Successful!“);
}?catch?(Exception?e)?{
//?TODO?Auto-generated?catch?block
System.out.println(e.getMessage());
}
}
private?void?E()?throws?Exception{
T();
Ep();
}
private?void?Ep()?throws?Exception{
if(statement.charAt(index)==‘+‘||statement.charAt(index)==‘-‘){
index++;
T();
Ep();
}else{
if(statement.charAt(index)==‘)‘&&kuohu%2!=1)
throw?new?Exception(“括號匹配錯誤“);
if(statement.charAt(index)!=‘#‘&&statement.charAt(index)!=‘)‘)
throw?new?Exception(“存在非法符號!“);
}
}
private?void?T()?throws?Exception{
F();
Tp();
}
private?void?Tp()?throws?Exception{
if(statement.charAt(index)==‘*‘||statement.charAt(index)==‘/‘){
index++;
F();
Tp();
}else{
if(statement.charAt(index)==‘)‘&&kuohu%2!=1)
throw?new?Exception(“括號匹配錯誤“);
if(statement.charAt(index)!=‘#‘&&statement.charAt(index)!=‘)‘&&statement.charAt(index)!=‘+‘&&statement.charAt(index)!=‘-‘)
throw?new?Exception(“存在非法符號!“);
}
}
private?void?F()?throws?Exception{
int?flag=0;
if(statement.charAt(index)==‘(‘){
kuohu++;
index++;
E();
if(statement.charAt(index)!=‘)‘){
throw?new?Exception(“括號匹配錯誤!“);
}
kuohu--;
index++;
return;
}
if(statement.charAt(index)<=‘9‘&&statement.charAt(index)>=‘0‘){
index++;
while((statement.charAt(index)<=‘9‘&&statement.charAt(index)>=‘0‘)||statement.charAt(index)==‘.‘){
if(statement.charAt(index)==‘.‘){
if(flag==1){
throw?new?Exception(“浮點數錯誤!“);
}
flag++;
}
index++;
}
return;
}
throw?new?Exception(“運算符錯誤!“);
}
}
?屬性????????????大小?????日期????時間???名稱
-----------?---------??----------?-----??----
?????文件????????2459??2012-12-15?16:12??Analysis.java
評論
共有 條評論