資源簡(jiǎn)介
一、實(shí)驗(yàn)?zāi)康?實(shí)現(xiàn)一個(gè)遞歸下降語(yǔ)法分析程序,識(shí)別用戶輸入的算術(shù)表達(dá)式。
二、實(shí)驗(yàn)主要內(nèi)容
1、文法如下:
ETE`
E’+TE’|-TE’|
TFT`
T’*FT’|/FT’|
F(E)|i
2、求取各非終結(jié)符的First及Follow集合
3、編程實(shí)現(xiàn)下降遞歸分析法,識(shí)別從鍵盤(pán)輸入的關(guān)于整數(shù)或浮點(diǎn)數(shù)的算術(shù)表達(dá)式(在此,上述文法中的i代表整數(shù)或浮點(diǎn)數(shù))
4、對(duì)于語(yǔ)法錯(cuò)誤,要指出錯(cuò)誤具體信息。

代碼片段和文件信息
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(“輸入出錯(cuò)!“);
}
}
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(“括號(hào)匹配錯(cuò)誤“);
if(statement.charAt(index)!=‘#‘&&statement.charAt(index)!=‘)‘)
throw?new?Exception(“存在非法符號(hào)!“);
}
}
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(“括號(hào)匹配錯(cuò)誤“);
if(statement.charAt(index)!=‘#‘&&statement.charAt(index)!=‘)‘&&statement.charAt(index)!=‘+‘&&statement.charAt(index)!=‘-‘)
throw?new?Exception(“存在非法符號(hào)!“);
}
}
private?void?F()?throws?Exception{
int?flag=0;
if(statement.charAt(index)==‘(‘){
kuohu++;
index++;
E();
if(statement.charAt(index)!=‘)‘){
throw?new?Exception(“括號(hào)匹配錯(cuò)誤!“);
}
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(“浮點(diǎn)數(shù)錯(cuò)誤!“);
}
flag++;
}
index++;
}
return;
}
throw?new?Exception(“運(yùn)算符錯(cuò)誤!“);
}
}
?屬性????????????大小?????日期????時(shí)間???名稱(chēng)
-----------?---------??----------?-----??----
?????文件????????2459??2012-12-15?16:12??Analysis.java
評(píng)論
共有 條評(píng)論