题解 | #坐标移动#

坐标移动

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

总体思路:把接收的字符串使用split处理成为;分割的多个子串,循环遍历所有子串,子串不合法的直接跳过,子串合法的对横纵坐标进行相应的操作。(处理子串分为处理首字母和首字母后的数字,用多个if判断子串的合法性)

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();
        int  strnum, x = 0, y = 0;
        String str1[] = str.split(";");
        for (int i = 0; i < str1.length; i++) {   //依据分割出的子串次数循环
            if (str1[i] != "" && str1[i].length() > 1 &&str1[i].substring(1) != "") {//首先判断不是空串,并且串的长度大于1(不判断这一步会导致str1[i].substring(1) != ""抛异常,当处理字符串长度为1的串时),最后判断首字母后的串不为空
                if (str1[i].charAt(0) == 'A' || str1[i].charAt(0) == 'W' ||
                        str1[i].charAt(0) == 'S' || str1[i].charAt(0) == 'D') {
                        try {
                            strnum = Integer.parseInt(str1[i].substring(1));//没抓到异常代表首字母后的数字合法不带有字母。
                            if (str1[i].charAt(0) == 'A') {
                                x = x  - strnum;
                            }
                            if (str1[i].charAt(0) == 'W') {
                                y = y  + strnum;
                            }
                            if (str1[i].charAt(0) == 'S') {
                                y = y  - strnum;
                            }
                            if (str1[i].charAt(0) == 'D') {
                                x = x  + strnum;
                            }
                        } catch (NumberFormatException
                                     e) {                         //如果抓异常证明后面的不是合法的纯数字

                        }
                }
            }

        }
        System.out.println(x + "," + y);
    }
}
//有不合理出敬请指出。

#刷题##java##华为OD#
全部评论

相关推荐

给🐭🐭个面试机会吧:我boss直聘天天有家教跟我打招呼😓
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务