示例代码:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int x = 0, y = 0;
String str = sc.next();
String string = str.toLowerCase();
String[] split = string.split(";");
for (String s : split) {
// 判断当前s是否有效
if (!s.matches("[wasd][1-9][0-9]?")) {
continue;
}
// 方向
String dir = s.substring(0, 1).toLowerCase();
// 移动距离
int dis = Integer.parseInt(s.replace(dir, ""));
switch (dir) {
case "w":
y += dis;
break;
case "a":
x -= dis;
break;
case "s":
y -= dis;
break;
case "d":
x += dis;
break;
default:
break;
}
}
System.out.println(x + "," + y);
}
代码详解:
1. 首先将输入字符串切分开,获得单个的每一步操作字符串;
2. 遍历所有操作字符串s,使用正则表达式判断 s 是否有效;
3. 根据wasd判断操作方向;