异常例题2


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;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值