思路
坐标系其实就是一个(x,y)的二元组。如果用python来解,这道题直接用元组就可以了。但是Java没有元组的概念,因此我们就需要构建一个元组。
接下来就是将输入按照;分隔符split成一个数组然后遍历操作就可以了。
代码
import java.util.ArrayList;
import java.util.Map;
import java.util.Scanner;
import java.util.StringJoiner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String operations = scanner.next();
String[] operationArr = operations.split(";");
Tuple<Integer, Integer> tuple = Tuple.of(0, 0);
for (String operation : operationArr) {
// 长度为2或者3
if (operation.length() == 2 || operation.length() == 3 && operation.charAt(0) >= 65 && operation.charAt(0) <= 90) {
if (isDigital(operation.substring(1))) {
// 开始运动
move(operation, tuple);
}
}
}
System.out.println(tuple);
}
}
private static boolean isDigital(String num) {
char[] chars = num.toCharArray();
for (char aChar : chars) {
if (!Character.isDigit(aChar)) {
return false;
}
}
return true;
}
private static Tuple<Integer, Integer> move(String operation, Tuple<Integer, Integer> tuple) {
String direction = operation.substring(0, 1);
int step = Integer.parseInt(operation.substring(1));
switch (direction) {
case "A":
tuple.l -= step;
break;
case "S":
tuple.r -= step;
break;
case "D":
tuple.l += step;
break;
case "W":
tuple.r += step;
break;
default:
}
return tuple;
}
}
class Tuple<L, R> {
L l;
R r;
private Tuple(L l, R r) {
this.l = l;
this.r = r;
}
static <L, R> Tuple<L, R> of(L l, R r) {
return new Tuple<>(l, r);
}
@Override
public String toString() {
return l + "," + r;
}
} 
京公网安备 11010502036488号