华为机考HJ17题解 | #坐标移动#

坐标移动

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);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
           String a = in.nextLine();
           Gis g=new Gis();
            if(null!=a&&a.length()>3){
                String[] str=a.split(";");
                for(String s:str){
                    g.moveGis(s);
                }
            }
            g.print();
        }
    }
   private static class Gis{
        private   int x;
        private   int y;
       public Gis(){
             this.x=0;
             this.y=0; 
        }
        public Gis(int x,int y){
             this.x=x;
             this.y=y; 
        }
        public void  moveGis(String zz){
            if(null==zz||zz.length()<2||zz.length()>3){
                return;
            }
            String flag=zz.substring(0,1);
            String left=zz.substring(1);
            if(!isNumeric(left)){
                return;
            }
            int num=Integer.parseInt(left);
            if(flag.equals("A")){
                this.x-=num;
            }else if(flag.equals("D")){
                this.x+=num;
            }else if(flag.equals("W")){
                this.y+=num;
            }else if(flag.equals("S")){
                this.y-=num;
            }
        }
        public void print(){
            System.out.println(this.x+","+this.y);
        }
        public static boolean isNumeric(String str) {
            try {
                Integer.parseInt(str);
                return true;
            } catch (NumberFormatException e) {
                return false;
            }
        }
    }
}
 

要点总结:

1 创建private static class Gis的位置类方便对定位进行调整;

2 排除掉不符合条件的定位指令信息;

#华为##华为机考#
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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