题解 | #坐标移动#

坐标移动

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

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();
        String[] moves = str.split(";");
        Point p = new Point(0, 0);
        for (String s : moves) {
            if (isValid(s)) {
                p.move(s);
            }
        }
        p.print();
    }

    public static boolean isValid(String s) {
        boolean flag = true;
        char[] chars = s.toCharArray();
        char c;
        int index = 0;
        if (s.isEmpty() || s.length() == 1) {
            flag = false;
        } else {
            while (index < chars.length) {
                c = chars[index];
                if (index == 0 && Character.isUpperCase(c)) {
                    index++;
                    continue;
                } else if (index > 0 && Character.isDigit(c)) {
                    index++;
                    continue;
                } else {
                    flag = false;
                    break;
                }
            }
        }
        return flag;
    }
}

class Point {
    private int X;
    private int Y;
    public Point(int x, int y) {
        this.X = x;
        this.Y = y;
    }

    public void move(String cmd) {
        char dir = cmd.charAt(0);
        int dis = Integer.parseInt(cmd.substring(1));
        switch (dir) {
            case 'W' :
                this.Y += dis;
                break;
            case 'A' :
                this.X -= dis;
                break;
            case 'S' :
                this.Y -= dis;
                break;
            case 'D' :
                this.X += dis;
                break;
        }
    }

    public void print() {
        System.out.printf("%d,%d", this.X, this.Y);
    }
}

全部评论

相关推荐

10-15 09:13
已编辑
天津大学 soc前端设计
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务