题解 | #坐标移动#
坐标移动
https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextLine()) { // 注意 while 处理多个 case
String str = in.nextLine();
String[] arr = str.split(";");
ArrayList<String> arrayList = new ArrayList<>();
for (String s : arr) {
if (s.startsWith("A") || s.startsWith("S") || s.startsWith("W") ||
s.startsWith("D")) {
if (s.length() == 3 || s.length() == 2) {
char[] chars;
if (s.length() == 3) {
chars = s.substring(1, 3).toCharArray();
} else {
chars = s.substring(1, 2).toCharArray();
}
boolean flag = true;
for (char ch : chars) {
if (!Character.isDigit(ch)) {
flag = false;
}
}
if (flag) {
arrayList.add(s);
}
}
}
}
//A表示向左移动,D表示向右移动,W表示向上移动,S表示向下移动
int x = 0;
int y = 0;
for (String s : arrayList) {
String startFlag = s.substring(0, 1);
int number;
if (s.length() == 3) {
number = Integer.parseInt(s.substring(1, 3));
} else {
number = Integer.parseInt(s.substring(1, 2));
}
switch (startFlag) {
case "A":
x = x - number;
break;
case "D":
x = x + number;
break;
case "W":
y = y + number;
break;
case "S":
y = y - number;
break;
default:
break;
}
}
System.out.println(x + "," + y);
}
}
}
查看12道真题和解析
