2. 设计一个函数, 接受一个点和一个字符串作为参数,点表示一个玩家所在的坐标,字符串可能包括 wasd, w 表示玩家向前移动 (纵坐标 +1), s 表示玩家向后移动, a 表示玩家向左移动 (横坐标 -1), d 表示玩家向右移动, 如果字符串中出现非 wasd 的字符, 则抛出一个异常,玩家一轮之多只能移动八次, 如果超出, 也抛出异常, 然后让用户重新输入。返回值: 一个点, 表示该玩家移动后的坐标
public class ParseInt { public static Point move(Point start, String input) { // 可重入性,无论该方法在运行过程中抛出何种异常,程序的状态不应该发生改变 if (input.length() > 8) { throw new RuntimeException(); } int x = start.getX(); int y = start.getY(); for (int i = 0; i < input.length(); ++i) { char ch = input.charAt(i); switch (ch) { case 'w': ++y; break; case 's': --y; break; case 'a': --x; break; case 'd': ++x; break; default: throw new RuntimeException(input + ":" + ch); } } return new Point(x, y); }
public static void main(String[] args) { Point start = new Point(0, 0); Scanner in = new Scanner(System.in); while (true) { try { Point end = move(start, in.nextLine()); System.out.println(end.getX() + ", " + end.getY()); break; } catch (RuntimeException e) { System.out.println("Invalid input, not moved. Please input again."); System.out.println(start.getX() + ", " + start.getY()); } } } }
class Point { private int x = 0; private int y = 0;
public Point(int x, int y) { this.x = x; this.y = y; }
public int getX() { return x; }
public void setX(int x) { this.x = x; }
public int getY() { return y; }
public void setY(int y) { this.y = y; }
public void translate(int deltaX, int deltaY) { this.x += deltaX; this.y += deltaY; } }