题解 | 坐标移动

坐标移动

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

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {

    public static boolean check(String str) {
        if (!str.matches("[WASD][0-9]{1,2}")) {
            return false;
        }
        return true;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        String cmd = in.nextLine();
        String[] str = cmd.split(";");
        int x = 0, y = 0;
        for (String s : str) {
            if (check(s)) {
                int val = Integer.valueOf(s.substring(1));
                switch (s.charAt(0)) {
                    case 'W':
                        y += val;
                        break;
                    case 'S':
                        y -= val;
                        break;
                    case 'A':
                        x -= val;
                        break;
                    case 'D':
                        x += val;
                        break;
                }
            }
        }
        System.out.print(x + "," + y);
    }


}

全部评论

相关推荐

06-07 21:26
江南大学 C++
话不多说,直接上时间线和图片1.2024年10月底发offer,并签三方2.2025年5月底公司违约
从零开始的转码生活:希望所有签了三方但直接违约的公司都倒闭!都倒闭!都倒闭!
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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