题解 | #坐标移动#

坐标移动

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

import java.util.Scanner;
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        int x = 0;
        int y = 0;
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            String str = in.nextLine();
            String[] strArr = str.split(";");
            for(String s: strArr){
                if(isValied(s)){
                    
                    String direction = s.substring(0,1);
                    int distance = Integer.valueOf(s.substring(1));
                   
                    if("A".equals(direction)){
                        x -= distance;
                    }
                    if("D".equals(direction)){
                        x += distance;
                    }
                    if("W".equals(direction)){
                        y += distance;
                    }
                    if("S".equals(direction)){
                        y -= distance;
                    }
                }
            }
        }
        System.out.print(String.format("%d,%d", x, y));
    }
    
    private static boolean isValied(String str){
        if(str.length() < 2){
            return false;
        }
        if(!Arrays.asList("A","S","W","D").contains(str.substring(0,1))){
            return false;
        }
        if(!str.substring(1).matches("[0-9]+")){
            return false;
        }
        
        return true;
    }
}

全部评论

相关推荐

点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务