日期:2014-05-20 浏览次数:20725 次
public class MovingProcessor { //所谓四面八方,把方向控制好就行了 //以2维坐标为参考,前为上(y坐标增加),右为右(x坐标增加),后为下(y坐标减少),左为左(x坐标减少) private static final int[][] MOVING_DIR = {{0,1}, {1,0}, {0,-1}, {-1,0}}; protected int dir = 0; //用于控制方向 protected double x = 0; //用于控制x坐标 protected double y = 0; //用于控制y坐标 private boolean isolating = true; //是否是独立的命令(用于扩展,此题可忽略),因为是每次独立计算距离(即后面的距离不累加前面的距离),所以本题设为独立命令 //private boolean realTime = false;//是否是实时处理(用于扩展,此题忽略) public MovingProcessor() {} public MovingProcessor(boolean isolating) { this.isolating = isolating; } public void reset() { //处理器重置 dir = 0; x = 0; y = 0; } public double execute(String cmd) throws Exception { //执行指令,支持小数距离(题目给的是整数距离,这里扩展支持小数距离) if (isolating) reset(); int dec = 0; //小数标志 double num = 0, times = 0; for (char c : cmd.toCharArray()) { //按字符遍历指令 if (c == 'L') { //遇到左转L指令 if (num > 0) {//判断是否L指令前是否存在移动距离,如果存在,则先移动 move(num); //移动距离 num = 0; dec = 0; } changeDir(c); //改变方向 } else if (c == 'R') { //遇到R右转指令 if (num > 0) { move(num); num = 0; dec = 0; } changeDir(c); } else if (c>='0' && c<='9') { //遇到数字累加数字 if (dec == 0) { //无小数的时候 num = num*10 + (c-'0'); } else { //有小数的时候 num += (c-'0')/times; times *= 10; } } else if (c == '.') { //遇到小数点 if (dec > 0) { //非法小数点则抛出异常 throw new Exception(String.format("Error Command[%s].", cmd)); } dec = 1; times = 10; } else { //非法字符则抛出异常 throw new Exception(String.format("Error Command[%s].", cmd)); } } if (num > 0) { //如果有移动距离就移动 move(num); } return Math.sqrt(x*x + y*y); //返回移动的距离 } protected void changeDir(char dir) { //改变方向 this.dir += (dir=='L' ? -1 : (dir=='R' ? 1 : 0)); } protected void move(double value) { //移动距离 dir %= 4; dir += (dir < 0) ? 4 : 0; x += value * MOVING_DIR[dir][0]; y += value * MOVING_DIR[dir][1]; } public static void main(String[] args) { String[] cmds = getCmds(); MovingProcessor mp = new MovingProcessor(); System.out.println("Execute Result:"); for (String cmd : cmds) { try { System.out.printf("%.2f\n", mp.execute(cmd)); } catch (Throwable e) { e.printStackTrace(); //break; //skip, ignore, cancel, so on... } } } public static String[] getCmds() { String[] cmds; int count = 0; Scanner sc = new Scanner(System.in); try { System.out.println("User Input:"); count = Integer.valueOf(sc.nextLine()).intValue(); } catch (Throwable e) { e.printStackTrace(); System.exit(-1); } cmds = new String[count]; for (count=0; count<cmds.length; count++) { cmds[count] = sc.nextLine(); } return cmds; } }