题解 | #坐标移动#
坐标移动
https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.nextLine();
// 分割字符串得到命令数组
String[] commands = str.split(";");
int x = 0, y = 0;
for (int i = 0; i < commands.length; i++) {
if (isValid(commands[i])) {
char dir = commands[i].charAt(0);
int len = Integer.parseInt(commands[i].substring(1));
if (dir == 'A') {
x -= len;
} else if (dir == 'D') {
x += len;
} else if (dir == 'W') {
y += len;
} else if (dir == 'S') {
y -= len;
}
}
}
System.out.print(x + "," + y);
}
// 检查命令是否有效
public static boolean isValid(String str) {
if (str.equals(" ") || str.length() > 3 || str.length() < 2) {
return false;
}
// 如果命令长度是3,检查要第三个字符
if (str.length() == 3 && !isDigit(str.charAt(2))) {
return false;
}
if (isLetter(str.charAt(0)) && isDigit(str.charAt(1))) {
return true;
}
return false;
}
// 检查命令的方向操作符是否有效
public static boolean isLetter(char c) {
if (c == 'A' || c == 'D' || c == 'W' || c == 'S') {
return true;
}
return false;
}
// 检查字符是否是数字
public static boolean isDigit(char c) {
if (c >= '0' && c <= '9') {
return true;
}
return false;
}
}
查看2道真题和解析