题解 | #坐标移动#

坐标移动

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

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[] strs = in.nextLine().split(";");
        int[] pos = {0, 0};

        for(String str : strs){
            if(validStr(str)){convert(str, pos);}
        }

        System.out.printf("%d,%d", pos[0], pos[1]);

    }

    public static boolean validStr(String str){
        if(str.equals("") || str.length() == 1 || str.length() > 3)return false;
        
        String str1 = str.substring(1);
        for(char c : str1.toCharArray()){
            if(!Character.isDigit(c))return false;
        }
        return true;
    }

    public static void convert(String str, int[] pos){
        char direct = str.charAt(0);
        int step = Integer.parseInt(str.substring(1));
        if(direct == 'A'){
            pos[0] -= step;
        }else if(direct == 'D'){
            pos[0] += step;
        }else if(direct == 'W'){
            pos[1] += step;
        }else if(direct == 'S'){
            pos[1] -= step;
        }
    }



}

全部评论

相关推荐

10-13 12:53
已编辑
湖北工业大学 前端工程师
小海c:包装一下,第一个感觉是字节青训营的那个,后面那个是黑马的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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