题解 | #坐标移动#

坐标移动

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);
        String[] operations = in.nextLine().split(";");
        int x = 0;
        int y = 0;
        int[] op = new int[2];
        for (String str : operations) {
            if (IsLegalOp((str))) {
                op = move(x,y,str);
                x = op[0];
                y = op[1];
            }
        }
        System.out.print(x+","+y);
    }

    public static boolean IsLegalOp(String op) {
        if (op.equals("")) {
            return false;
        }
        return op.matches("[WASD]\\d{1,2}");
    }

    public static int[] move(int x, int y, String op) {

        int distance = Integer.parseInt(op.substring(1, op.length()));

        if (op.charAt(0) == 'W') {
            y = y + distance;
        } else if (op.charAt(0) == 'A') {
            x = x - distance;
        } else if (op.charAt(0) == 'S') {
            y = y - distance;
        } else if (op.charAt(0) == 'D') {
            x = x + distance;
        }

        int[] res = new int[2];
        res[0] =x;
        res[1] = y;
        return res;
    }
}

全部评论

相关推荐

有趣的牛油果开挂了:最近这个阶段收到些杂七杂八的短信是真的烦
点赞 评论 收藏
分享
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务