题解 | #坐标移动#
坐标移动
https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29
import java.util.Scanner;
import java.lang.Integer;
import java.lang.Character;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
//赋初始值,x、y坐标均为0
int x = 0, y = 0;
Scanner in = new Scanner(System.in);
//读取字符串
String str = in.nextLine();
//分割成字符串数组,分隔符为;(注意是半角符号)
String[] operations = str.split(";");
//遍历字符串数组,无效的不处理,有效的将x、y坐标进行加减
//每个字符串item,1.不为空,2.首字母应为ADWS其中之一
//3.首字母之后的字符串应为1或2位的数字
for (String operation : operations) {
if (operation.isEmpty()) {
continue;
}
char direction = operation.charAt(0);
if (direction != 'A'
&& direction != 'D'
&& direction != 'W'
&& direction != 'S'
) {
continue;
}
String steps = operation.substring(1);
int stepsLen = steps.length();
if (stepsLen != 1 && stepsLen != 2) {
continue;
}
boolean allDigit = true;
for (int i = 0; i < stepsLen; i++) {
if (!Character.isDigit(steps.charAt(i))) {
allDigit = false;
break;
}
}
if (!allDigit) {
continue;
}
int intSteps = Integer.parseInt(steps);
switch (direction) {
case 'A':
x -= intSteps;
break;
case 'D':
x += intSteps;
break;
case 'W':
y += intSteps;
break;
case 'S':
y -= intSteps;
break;
default:
break;
}
}
System.out.print(x + "," + y);
}
}
