华为机试——坐标移动

细节点

  • 利用异常来处理位移的转换

代码

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int x = 0;
        int y = 0;
        String s = in.nextLine();
        ArrayList<String> list = new ArrayList();
        StringBuilder sb = new StringBuilder();
        for(char c : s.toCharArray()){
            if(c == ';'){
                list.add(sb.toString());
                sb.delete(0,sb.length());
            }else{
                sb.append(c);
            }
        }
        
        for(String ss : list){
            if(ss == null || ss.length() < 2 || ss.length() > 3){
                continue;
            }
            int move = 0;
            try{
                move = new Integer(ss.substring(1));
            }catch(NumberFormatException e){
                continue;
            }
            char c = ss.charAt(0);
            if(c == 'A')
                x -= move;
            else if(c == 'D')
                x += move;
            else if(c == 'W')
                y += move;
            else if(c == 'S')
                y -= move;
        }
        System.out.println(x + "," + y);
    }
}
上一篇:小学生四则运算


下一篇:Jmeter学习-时间获取