题解 | #坐标移动#
坐标移动
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 的区别 int[] coordinate = {0, 0}; while (in.hasNextLine()) { // 注意 while 处理多个 case String str = in.nextLine(); String[] strArr = str.split(";"); // int[] coordinate = {0,0}; for (int i = 0; i < strArr.length; i++) { String tempStr = strArr[i]; if (isLegal(tempStr)) { if (tempStr.length() == 0) { continue; } else { char key = tempStr.charAt(0); int displaceDistance = Integer.valueOf(tempStr.substring(1)); switch (key) { case 'A': coordinate[0] -= displaceDistance; break; case 'D': coordinate[0] += displaceDistance; break; case 'S': coordinate[1] -= displaceDistance; break; case 'W': coordinate[1] += displaceDistance; break; default: break; } } } else { continue; } } System.out.print(coordinate[0] + "," + coordinate[1]); } } public static boolean isLegal(String str) { // int length = str.length(); switch (length) { case 0: return true; case 1: return false; case 2: if (str.charAt(0) == 'A' || str.charAt(0) == 'W' || str.charAt(0) == 'S' || str.charAt(0) == 'D') { if (str.charAt(1) >= '0' && str.charAt(1) <= '9') { return true; } else { return false; } } else { return false; } default: if (str.charAt(0) == 'A' || str.charAt(0) == 'W' || str.charAt(0) == 'S' || str.charAt(0) == 'D') { if (str.charAt(1) >= '1' && str.charAt(1) <= '9') { for (int i = 2; i < str.length(); i++) { if (str.charAt(i) >= '0' && str.charAt(i) <= '9') { continue; } else { return false; } } return true; } else { return false; } } else { return false; } } } }