题解 | #坐标移动#
坐标移动
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);
int x = 0;
int y = 0;
String str = in.nextLine();
String[] strs = str.split(";");
for(String s:strs){
//String.matches()正则匹配
if(s.matches("[WASD][0-9]{1,2}")){
//substring(int beginIndex, int endIndex)
//Integer.valueOf()将String为int类型
int val = Integer.valueOf(s.substring(1));
switch(s.charAt(0)){
case 'W':
y += val;
break;
case 'S':
y -= val;
break;
case 'A':
x -= val;
break;
case 'D':
x += val;
break;
}
}
}
System.out.println(x+","+y);
}
}
要熟练默写下面三个常用方法:
①String.matches()正则匹配,通过"[WASD][0-9]{1,2}"匹配出合法的输入
②substring(int beginIndex, int endIndex),substring(int beginIndex)截取字符串
③Integer.valueOf()将String转为int,并且可以将"02"转为2
