题解 | 坐标移动

坐标移动

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

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        // 难点分析:1 输入处理 2 非法处理
        Scanner sc = new Scanner(System.in);
        // 1. 输入处理,用什么存储,数组?list?
        String str = sc.next();
        String[] strs = str.split(";");
        int x=0,y=0;
        
        for(String s:strs)
        {
            // 2. 非法处理
            if(s == null || s.trim().length() == 0) continue;
            String s1 = s.substring(0,1);

            if(!"A".equals(s1) && !"D".equals(s1) && !"W".equals(s1) && !"S".equals(s1) ) continue;

           
            // 校验是否是纯数字
            String numStr = s.substring(1);
            boolean allDigit = true;
            for(int i =0;i<numStr.length();i++)
            {
                if(!Character.isDigit(numStr.charAt(i))){
                    allDigit = false;
                    break;
                }
            }
            if(!allDigit) continue;

            int mv =0;
            try{
                 mv = Integer.parseInt(numStr);
            }catch(Exception e)
            {
                continue;
            }
            if(mv<1|| mv>99) continue;
            
            if ("A".equals(s1)) {
                x = x - mv;
            } else if ("S".equals(s1)) {
                y = y - mv;
            } else if ("W".equals(s1)) {
                y = y + mv;
            } else if ("D".equals(s1)) {
                x = x + mv;
            }
        }
        // 3 正常处理
        System.out.println(x+","+y);
    }
}

正确考虑了各种非法情况

全部评论

相关推荐

mama3925:灵神是天才,路线不适合正常人
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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