您的位置:首页 > 编程语言 > C语言/C++

设计一个有限状态机提取C语言文件中的注释(java版)

2014-10-10 15:47 441 查看
这是一道百度笔试题目:设计一个有限状态机提取C语言文件中的注释

这道题其实也是考了23种设计模式中状态模式



Java实现代码:

import java.util.ArrayList;

interface state{
void handle(context con);
}
class text implements state{                              //文本状态
public void handle(context con){
if(con.getChar()=='/'){
con.setState(new slash());
}
}
}
class slash implements state{                              //有一个"/"
public void handle(context con){
if(con.getChar()=='*'){
con.setState(new bc_comment());	               //若再有一个“*”转到块注释(block)处理状态
}else if(con.getChar()=='/'){
con.setState(new ln_comment());                //若再有一个“/”转到行注释处理状态
}else{
con.setState(new text());
}
}
}
class ln_comment implements state{
public void handle(context con){
if(con.getChar()=='\n'){                            //行注释处理时遇到换行,返回文本状态
con.setState(new text());
}else{
System.out.println("//comment: "+con.getChar());
}
}
}
class bc_comment implements state{
public static ArrayList<Character> ls=new ArrayList<Character>();
public void handle(context con){
if(con.getChar()=='*'){
con.setState(new start_comment());
}else{
con.setState(new bc_comment());
ls.add(con.getChar());
System.out.println("/* */comment:"+con.getChar());
}
}
}
class start_comment implements state{
public void handle(context con){
if(con.getChar()=='/'){
con.setState(new text());
}
}
}
class context{
public state s;
public char ch;
public context(state s){
this.s=s;
}
public void setChar(char ch){
this.ch=ch;
}
public void setState(state s){
this.s=s;
}
public char getChar(){
return this.ch;
}
public void handle(){
s.handle(this);
}
}

public class stateDemo {
public static void main(String args[]){
String str="s//najkknsa\na,a,,";
state sta=new text();
char[] ch=str.toCharArray();
context con=new context(sta);
for(int j=0;j<str.length();j++){
con.setChar(ch[j]);
con.handle();
}
}
}


ps:上述情况,没考虑行注释和块注释嵌套的情况。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐