您的位置:首页 > 编程语言 > Java开发

java笔试题--Java实现命令编辑器

2012-10-09 23:27 369 查看
题目:假定有一命令编辑框,可以接受两种命令:【type x】和【undo n】。x代表输入文本,n代表秒数。type命令用于当输入文本,而undo命令用于撤销操作。输入undo 1,表示向前撤销1秒。撤销操作可以指定撤销到当前时间之前操作的时间,并且撤销操作对自身同样有效。

例子:

命令输入的时间命令显示结果
1type aa
2type bab
3type cabc
4undo 1ab
5undo 1a
实现代码如下:

package javatest;

import java.util.HashMap;
import java.util.Map;

class CmdException extends RuntimeException {

private static final long serialVersionUID = 8562504939570096319L;

public CmdException() {
super();
}

public CmdException(String message, Throwable cause) {
super(message, cause);
}

public CmdException(String message) {
super(message);
}

public CmdException(Throwable cause) {
super(cause);
}

}

/**
* @author NiluChen
*
*/
public class CommandEditor {

private static final String TYPE_PATTERN = "\\s*(type|TYPE)\\s+\\w+\\s*";
private static final String UNDO_PATTERN = "\\s*(undo|UNDO)\\s+\\d+\\s*";

/**
*
* @param cmds 命令
* @param times 时间点
* @return String 返回结果
* @throws IllegalArgumentException
*/
public static String cmdEditor(String[] cmds, int[] times)
throws IllegalArgumentException {
// 使用map缓存了每次操作后的时间点和结果
Map<Integer, String> resultBuffer = new HashMap<Integer, String>();
// 文本内容
String text = "";
for (int i = 0; i < cmds.length; i++) {
String cmd = cmds[i].trim();
if (cmd.matches(CommandEditor.TYPE_PATTERN)) {
String[] strs = cmd.split("\\s+");
text += strs[1];
resultBuffer.put(times[i], text);
} else if (cmd.matches(CommandEditor.UNDO_PATTERN)) {
int undoTime = Integer.parseInt(cmd.split("\\s+")[1]);
if (undoTime > times[i])
throw new CmdException("参数不合法!");
// 撤销时间点
int rollbackTime = times[i] - undoTime - 1;
// 执行撤销
while (!resultBuffer.containsKey(rollbackTime))
rollbackTime--;
resultBuffer.put(times[i], resultBuffer.get(rollbackTime));
} else
throw new CmdException("参数不合法!");
}
return resultBuffer.get(times[times.length - 1]);
}

/**
* @param args
*/
public static void main(String[] args) {

String[] cmds = { "type a", "type btg", "type c", "undo 1", "undo 2" };
int[] times = { 1, 2, 3, 4, 5 };
String result = CommandEditor.cmdEditor(cmds, times);
System.out.println(result);
System.out.println(result.equals("abtg"));
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: