题解 | #HJ17 坐标移动#

坐标移动

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

import java.util.*;

public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextLine()) {
            String s = in.nextLine();
            String[] strs = s.split(";");
            int x = 0;
            int y = 0;
            for (int i = 0; i < strs.length; i++) {
                //检验合法坐标
                if (strs[i].length() < 2 || strs[i].length() > 3) {
                    continue;
                }

                char direction = strs[i].charAt(0);
                String coordinateStr = strs[i].substring(1);
                int coordinate = 0;
                //转化坐标字符串为数字
                try {
                    coordinate = Integer.parseInt(coordinateStr);
                } catch (Exception e) {
                    continue;
                }
                //判断计算坐标
                switch (direction) {
                    case 'A':
                        x -= coordinate;
                        break;
                    case 'D':
                        x += coordinate;
                        break;
                    case 'W':
                        y += coordinate;
                        break;
                    case 'S':
                        y -= coordinate;
                        break;
                    default:
                        break;
                }
            }
            System.out.println(x + "," + y);
        }
    }

}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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