具体实现程序:
import java.util.Scanner;
public class Analyze_terms {
private String keyWord[] = {"for","if","then","else","while","do"};
private char ch;
//判断是否是关键字
boolean isKey(String str)
{
for(int i = 0;i < keyWord.length;i++)
{
if(keyWord[i].equals(str))
return true;
}
return false;
}
//判断是否是字母
boolean isLetter(char letter)
{
if((letter >= 'a' && letter <= 'z')||(letter >= 'A' && letter <= 'Z'))
return true;
else
return false;
}
//判断是否是数字
boolean isDigit(char digit)
{
if(digit >= '0' && digit <= '9')
return true;
else
return false;
}
//分析方法
void analyze(char[] chars)
{
String arr = "";
for(int i = 0;i< chars.length;i++) {
ch = chars[i];
arr = ""; //每次都重置这个字符串,用来接收所得到的语句
if(ch == ' '||ch == '\t'||ch == '\n'||ch == '\r'){}//除空格之内的
else if(isLetter(ch)){
while(isLetter(ch)||isDigit(ch)){
arr += ch;
ch = chars[++i];
}
//回退一个字符
i--;
if(isKey(arr)){
//关键字
if( arr.equals(keyWord[1])){
System.out.println("("+arr+","+"2"+")");
}else if(arr.equals(keyWord[2]))
System.out.println("("+arr+","+"3"+")");
else if(arr.equals(keyWord[3])){
System.out.println("("+arr+","+"4"+")");
}else if(arr.equals(keyWord[5])){
System.out.println("("+arr+","+"6"+")");
}else if(arr.equals(keyWord[0])){
System.out.println("("+arr+","+"1"+")");
}
}
else{
//标识符
System.out.println("("+arr+","+"10"+")");
}
}
else if(isDigit(ch)||(ch == '.'))
{
while(isDigit(ch)||(ch == '.'&&isDigit(chars[++i])))
{
if(ch == '.') i--;
arr = arr + ch;
ch = chars[++i]; //主要原因:把数字后的字符当做判断是否为多位数的条件,导致数字后的字符都没有了。
if(!(isDigit(ch)||ch == '.')) {
i--;
}
}
//无符号常数
System.out.println("("+arr+","+"11"+")");
}
else switch(ch){
//运算符
case '+':System.out.println("("+ch+","+"13"+")");break;
case '-':System.out.println("("+ch+","+"14"+")");break;
case '*':System.out.println("("+ch+","+"15"+")");break;
case '/':System.out.println("("+ch+","+"16"+")");break;
//分界符
case '(':System.out.println("("+ch+","+"27"+")");break;
case ')':System.out.println("("+ch+","+"28"+")");break;
case ';':System.out.println("("+ch+","+"26"+")");break;
//运算符
case '=':{
ch = chars[++i];
if(ch == '=')System.out.println("("+"=="+","+"25"+")");
else {
System.out.println("("+"="+","+"18"+")");
i--;
}
}break;
case ':':{
ch = chars[++i];
System.out.println("("+":"+","+"17"+")");
i--;
}break;
case '>':{
ch = chars[++i];
if(ch == '=')System.out.println("("+">="+","+"24"+")");
else {
System.out.println("("+">"+","+"21"+")");
i--;
}
}break;
case '<':{
ch = chars[++i];
if(ch == '=')System.out.println("("+"<="+","+"22"+")");
else if(ch == '>')System.out.println("("+"<>"+","+"23"+")");
else {
System.out.println("("+"<"+","+"20"+")");
i--;
}
}break;
//无识别
default: System.out.println("("+ch+","+"0"+")");
}
}
}
public static void main(String[] args) throws Exception {
System.out.println("请输入语句(以#结束):");
Scanner sc = new Scanner(System.in);
sc.useDelimiter("#");
String str = sc.next();
char [] term = str.toCharArray();
new Analyze_terms().analyze(term);
sc.close();
}
}
输入:
结果: