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

这是一道百度笔试题目:设计一个有限状态机提取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:上述情况,没考虑行注释和块注释嵌套的情况。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值