题解 | 坐标移动
坐标移动
https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int x = 0;
int y = 0;
// 遍历 scanner 的输入,当遍历到 ";" 字符时,进行分割且将分割的结果存入一个数组中
String s = scanner.nextLine();
String[] strings = s.split(";");
// 遍历数组中的每一个元素
for (int i = 0; i < strings.length; i++) {
// 检查字符串是否为空或长度不足
if (strings[i].length() < 2) {
continue; // 跳过长度不足的字符串
}
// 判断第一个字符是否为 W, A, S, D 中的一个
char firstChar = strings[i].charAt(0);
if (firstChar == 'A' || firstChar == 'D' || firstChar == 'W' || firstChar == 'S') {
// 判断第二个字符是否为数字
if (strings[i].charAt(1) >= '0' && strings[i].charAt(1) <= '9') {
// 判断字符串长度是否为 2 或 3
if (strings[i].length() == 2) {
int value = strings[i].charAt(1) - '0'; // 单个数字
switch (firstChar) {
case 'A':
x -= value;
break;
case 'D':
x += value;
break;
case 'W':
y += value;
break;
case 'S':
y -= value;
break;
}
} else if (strings[i].length() == 3) {
// 判断第三个字符是否为数字
if (strings[i].charAt(2) >= '0' && strings[i].charAt(2) <= '9') {
int value = (strings[i].charAt(1) - '0') * 10 + (strings[i].charAt(2) - '0'); // 两位数
switch (firstChar) {
case 'A':
x -= value;
break;
case 'D':
x += value;
break;
case 'W':
y += value;
break;
case 'S':
y -= value;
break;
}
}
}
}
}
}
System.out.println(x + "," + y);
}
}


查看2道真题和解析