题解 | #坐标移动#

坐标移动

https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29

import java.util.*;

// 注意类名必须为 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 str = in.nextLine();

            String[] arr = str.split(";");

            ArrayList<String> arrayList = new ArrayList<>();
            for (String s : arr) {
                if (s.startsWith("A") || s.startsWith("S") || s.startsWith("W") ||
                        s.startsWith("D")) {
                    if (s.length() == 3 || s.length() == 2) {
                        char[] chars;
                        if (s.length() == 3) {
                            chars = s.substring(1, 3).toCharArray();
                        } else {
                            chars = s.substring(1, 2).toCharArray();
                        }

                        boolean flag = true;
                        for (char ch : chars) {
                            if (!Character.isDigit(ch)) {
                                flag = false;
                            }
                        }
                        if (flag) {
                            arrayList.add(s);
                        }
                    }
                }
            }
            //A表示向左移动,D表示向右移动,W表示向上移动,S表示向下移动
            int x = 0;
            int y = 0;
            for (String s : arrayList) {
                String startFlag = s.substring(0, 1);
                int number;
                if (s.length() == 3) {
                    number = Integer.parseInt(s.substring(1, 3));
                } else {
                    number = Integer.parseInt(s.substring(1, 2));
                }

                switch (startFlag) {
                    case "A":
                        x = x - number;
                        break;
                    case "D":
                        x = x + number;
                        break;
                    case "W":
                        y = y + number;
                        break;
                    case "S":
                        y = y - number;
                        break;
                    default:
                        break;
                }
            }
            System.out.println(x + "," + y);

        }
    }
}

全部评论

相关推荐

迷茫的大四🐶:价格这么低都能满了?
点赞 评论 收藏
分享
用微笑面对困难:你出于礼貌叫了人一声大姐,大姐很欣慰,她真把你当老弟
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务