宋词密码在手3秒作诗赋词 Java版本 闲来蛋疼练练手

最近看了一篇文章,说一网友算出99个宋词常用语,然后根据给出的数字找到相应的词就可以在3秒内作诗赋词,觉得挺有意思的,给出一组数字然后自己去找太慢了,于是自己写了一个类,呵呵,纯属练手
http://blog.sina.com.cn/s/blog_51508bd70102dt7j.html 这是那篇文章

代码很简单,就是切割字符串,递归,循环
public class EasyDecode {
	
	private static Map<String, String> data = new HashMap<String, String>();
	
	/**
	 * 读取文件初始化数据
	 * 按行读取
	 */
	public static void init(){
		File file=new File("F:/code.txt");
		BufferedReader reader=null;
		try {
			reader = new BufferedReader(new FileReader(file));
			String tempString=null;
			while((tempString=reader.readLine())!=null){
				String[] sTemp = tempString.split(" ");
				data.put(sTemp[0], sTemp[1]);
			}
			reader.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			if(reader!=null){
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/** main方法
	 * @param args
	 */
	public static void main(String[] args) {
		init();
		String s="251182408"; //输出“相逢相思时候不见西风” 本人qq,好悲伤啊
		Decode(s);
	}
	
	/** 递归切割
	 * @param numStr
	 */
	public static void Decode(String numStr){
		String code =strSplit(numStr);
		if(!numStr.equals("")){
			Decode(code);
		}
	}
	
	/** 分割字符串,切割三次 大数字优先(如"226" 22是一个码,2是一个码,226应该分割为22,6而不是2,2,6)
	 *  返回切割后的字符串
	 *  宋词高频词汇和数字代码对应有限 ,出现数字0时情况比较特殊
	 *  如: 19880505 切割拼接最终为 1988505
	 *      22006 切割拼接最终为 226
	 * @param str
	 * @return
	 */
	public static String strSplit(String str){
		String strReturn="";
		for(int i=3;i>0;i--){
			if(str.length()>=i){
				String stemp = str.substring(0,i);
				if(findKey(stemp)){
					if(str.length()!=1){
						strReturn = str.substring(i,str.length());
					}
					break;
				}else{
					if(i==1){
						strReturn = str.substring(1,str.length());
					}
				}
			}
		}
		return strReturn;
	}
	
	
	/** 循环map,根据键查找值 返回布尔值
	 * @param keyIn 键
	 * @return
	 */
	public static boolean findKey(String keyIn){
		boolean isHere=false;
		for(Iterator<String> i=data.keySet().iterator();i.hasNext();){
			String st= (String)i.next();
			if(st.equals(keyIn)){
				System.out.print(data.get(keyIn));
				isHere=true;
				break;
			}
		}
		return isHere;
	}
	
}

那个txt里面就是一些词和数字的对应
如:
1 空
21 一笑
41 深处
纯属自我娱乐,作个记录,呵呵

你可能感兴趣的:(java)