题解 | 坐标移动

坐标移动

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 line = in.nextLine();

        String[] arr = line.split(";");
        // 标记x,y
        int x = 0, y = 0;
        for (int i = 0; i < arr.length; i++) {
            String str = arr[i];

            if (Objects.equals(str, "") || str == null) continue;
            char op = str.charAt(0);
            String step = str.substring(1);
            // 判断指令是否合法
            if (op != 'A' && op != 'D' && op != 'W' && op != 'S' ||
                    !isNumeric(step)) continue;

            int stepCount = Integer.parseInt(step);
            switch (op) {
                case 'A':
                    x -= stepCount;
                    break;
                case 'D':
                    x += stepCount;
                    break;
                case 'W':
                    y += stepCount;
                    break;
                case 'S':
                    y -= stepCount;
                    break;
            }
        }

        System.out.println(x + "," + y);
    }

    public static boolean isNumeric(String str) {
        if (str == null || str.isEmpty()) {
            return false;
        }
        for (int i = 0; i < str.length(); i++) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }
}

全部评论

相关推荐

码农索隆:以下是我以我微薄的认知提供的建议: 1.考个教师资格证,去当体育考试。 2.去健身房当健身教练(因为在我印象里面体育生身材都不错)。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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