题解 | 坐标移动
坐标移动
https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29
import java.util.HashMap; import java.util.Map; import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { static char[] directions = {'A','S','W','D'}; static Map<Character,int[]> map = new HashMap<>(); public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 String[] strs = in.nextLine().split(";"); int x = 0; int y = 0; map.put('A', new int[]{-1, 0}); map.put('S', new int[]{0, -1}); map.put('W', new int[]{0, 1}); map.put('D', new int[]{1, 0}); for(int i = 0; i < strs.length; i++){ if(isValid(strs[i])){ int number = Integer.parseInt(strs[i].substring(1)); int[] move = map.get(strs[i].charAt(0)); x += move[0] * number; y += move[1] * number; } } System.out.print(x + "," + y); } public static boolean isValid(String str){ int n = str.length(); if( n < 2 || n >3){ return false; } boolean found = false; boolean digitfound =false; for(char direction : directions){ if(str.charAt(0) == direction){ found = true; break; } } try{ if(Integer.parseInt(str.substring(1,str.length())) >= 1 || Integer.parseInt(str.substring(1,str.length())) <= 99){ digitfound = true; } }catch (Exception e){ return false; } return digitfound && found; } }