题解 | 坐标移动
坐标移动
https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
int x = 0, y = 0;
String []list = in.nextLine().split(";");
for (int i = 0; i < list.length; i++) {
String command = list[i];
if (!checkValid(command)) {
continue;
}
Character direction = command.charAt(0);
String intStr = command.substring(1);
int distance = Integer.parseInt(intStr);
switch (direction) {
case 'W':
y += distance;
break;
case 'A':
x -= distance;
break;
case 'S':
y -= distance;
break;
case 'D':
x += distance;
break;
default:
break;
}
}
System.out.print(x + "," + y);
}
public static boolean checkValid(String command) {
String regex = "^[ASWD]([1-9]|[1-9][0-9])$";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(command);
if (m.matches()) {
return true;
} else {
return false;
}
}
}
传音控股公司福利 338人发布
