题解 | #坐标移动#
坐标移动
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);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextLine()) { // 注意 while 处理多个 case
String a = in.nextLine();
String[] b = a.split(";");
int x = 0;
int y = 0;
for (int i = 0; i < b.length; i++) {
String su = b[i];
if (su.matches("[WASD][0-9]{1,2}")) { //重点在于此处,题目说两位数以内,个人误以为是一定要两个数位,比如如果是1,那坐标应该输入成01,结果就在正则里少了一种可行坐标校验,导致上传后怎么试都提示错误,后面才发现确实是理解错了,在正则表达式内加上正确情况的补充条件就通过了~
switch (su.charAt(0)) {
case 'A' :
int t1 = Integer.valueOf(su.substring(1));
x -= t1;
break;
case 'D' :
t1 = Integer.valueOf(su.substring(1));
x += t1;
break;
case 'W' :
t1 = Integer.valueOf(su.substring(1));
y += t1;
break;
case 'S' :
t1 = Integer.valueOf(su.substring(1));
y -= t1;
break;
}
}
}
System.out.println(x + "," + y);
}
}
}
查看12道真题和解析