题解 | 坐标移动-不使用正则表达式,利用Java的异常来处理字符串转数字

坐标移动

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);
        String str=in.nextLine();
        String[] strs=str.split(";");
        int x=0;int y=0;
        for(int i=0;i<strs.length;i++){
		  //利用Java的异常来处理字符串转数字
            if(strs[i].length()>=4||strs[i].length()<=1){
                continue;
            }
            int step=0;
            try{
                step=Integer.valueOf(strs[i].substring(1));
            }catch(Exception e){
                continue;
            }
            
            switch(strs[i].charAt(0)){
                case 'A':x=x-step;
                break;
                case 'D':x=x+step;
                break;
                case 'W':y=y+step;
                break;
                case 'S':y=y-step;
                break;
            }
        }
        System.out.println(x+","+y);

    }
}

全部评论

相关推荐

求个付费实习岗位:这种就是吃满时代红利又没啥技术水平,只能靠压力学生彰显优越感的老登,别太在意了
点赞 评论 收藏
分享
2025-12-22 16:31
已编辑
桂林电子科技大学 Python
很奥的前端仔:如果你接了offer 临时又说不去 hr确实要多做一些工作。 当然如果是接offer之前当我没说
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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