题解 | #坐标移动#

坐标移动

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

import java.util.*;

public class Main {
    static int x = 0;
    static int y = 0;
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String s = in.nextLine();
            String[] words = s.split(";");
            for (String word : words) {
                if (validate(word)) {
                    handle(word);
                }
            }
            System.out.println(x+ "," + y);
        }
    }

    private static void handle(String str) {
        String dir =  str.substring(0,1);
        int num = Integer.parseInt(str.substring(1));
        switch (dir) {
            case "A": x -= num ; break;
            case "D": x += num; break;
            case "W": y += num; break;
            case "S": y -= num; break;
        }
    }
    private static boolean validate (String str){
        if (str.length() == 0) return false;
        String dir = str.substring(0,1);
        String num = str.substring(1);
        if (!dir.equals("A") &&
                !dir.equals("D") && !dir.equals("W") && !dir.equals("S") ) {
            return false;
        }
        try {
            Integer integer = Integer.parseInt(num);
            if (integer < 100){
                return true;
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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