题解 | #坐标移动#

坐标移动

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

使用正则表达式来进行匹配

[abc] 只能匹配一个字符

[0-9]{1,2} 匹配0-9的字符,出现一次或者两次

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        String str = in.nextLine();
        String[] points = str.split(";");
        String letter = "";
        int pos = 0;
        int x = 0;
        int y = 0;
        for (String point : points) {
            //正则匹配
            String regex = "[ASDW][0-9]{1,2}";
            if (point.matches(regex)) {
                letter = point.substring(0, 1);
                pos = Integer.parseInt(point.substring(1));
                switch (letter) {
                    case "A" :
                        x += -1*pos;
                        y += 0;
                        break;
                    case "S" :
                        x += 0;
                        y += -1*pos;
                        break;
                    case "D" :
                        x += pos;
                        y += 0;
                        break;
                    case "W" :
                        x += 0;
                        y += pos;
                        break;
                }
            }
        }
        System.out.println(x+","+y);

    }
}

全部评论

相关推荐

06-15 18:44
黄淮学院 Java
Lynn012:如果是居民楼还是算了吧,看着有点野呢
点赞 评论 收藏
分享
06-10 21:15
门头沟学院 Java
宁阿:好多这种没🧠的公司,他们估计都不知道毕业的人不能给安排实习岗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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