import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String line = sc.nextLine();
String[] arr = line.split(";");
int x = 0;
int y = 0;
for (String s : arr) {
// 过滤非法字符结果
int length = s.length();
if (length < 2) {
continue;
}
String reduceRemove = s.replaceAll("[ADWS]", "");
if (length - reduceRemove.length() > 1) {
continue;
}
String invalidStr = s.replaceAll("[ADWS0-9]", "");
if (invalidStr.length() > 0) {
continue;
}
switch (s.charAt(0)) {
case 'A':
x -= Integer.parseInt(s.substring(1));
break;
case 'D':
x += Integer.parseInt(s.substring(1));
break;
case 'W':
y += Integer.parseInt(s.substring(1));
break;
case 'S':
y -= Integer.parseInt(s.substring(1));
break;
}
}
System.out.println(x + "," + y);
}
sc.close();
}
}
更简洁的写法:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String line = sc.nextLine();
String[] arr = line.split(";");
int x = 0;
int y = 0;
for (String s : arr) {
// 过滤非法字符结果
if (!s.matches("[ADWS][0-9]{1,5}")) {
continue;
}
int digit = Integer.parseInt(s.substring(1));
switch (s.charAt(0)) {
case 'A':
x -= digit;
break;
case 'D':
x += digit;
break;
case 'W':
y += digit;
break;
case 'S':
y -= digit;
break;
}
}
System.out.println(x + "," + y);
}
sc.close();
}
}