【华为机试018】坐标移动

题目描述:

开发一个坐标计算工具, A表示向左移动,D表示向右移动,W表示向上移动,S表示向下移动。从(0,0)点开始移动,从输入字符串里面读取一些坐标,并将最终输入结果输出到输出文件里面。

Java实现:

/*先把字符串用;分隔
*再依次判断坐标是否有效
*无效直接跳过
*有效进行switch case判断并移动坐标点
*/

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
        String input = sc.nextLine();
        if (input == "") continue;
        String[] list = input.split(";"); 
       
        int x = 0;
        int y = 0;
        for (int i = 0; i < list.length; i++) {
            if (list[i].matches("[ASDW]\\d{1,2}")) {
                char dir = list[i].charAt(0);
                int num = Integer.parseInt(list[i].substring(1,list[i].length()));
                switch(dir){
                    case 'A' :
                        x -= num;
                        break;
                    case 'D' :
                        x += num;
                        break;
                    case 'W' :
                        y += num;
                        break;
                    case 'S' :
                        y -= num;
                        break;
                }
            }
        }
        System.out.println(x + "," + y);//用system.out.printf()会报错
    }
    }
    /*
   static Boolean isValid(String s) {
        if (s == "") {
            return false;
        }
        
        if (s.length() > 3 || s.length() < 2) {
            return false;
        }
        
        if (s.charAt(0) != 'A' && s.charAt(0) != 'D' && s.charAt(0) != 'W' && s.charAt(0) != 'S') {
            return false;
        }
        
        if (s.charAt(1) < '0' || s.charAt(1) > '9') {
            return false;
        }
        
        if (s.length() == 3 && (s.charAt(2) < '0' || s.charAt(2) > '9')) {
            return false;
        }
        
        return true;
    }
    */
}

知识点:

  • 将自己实现的判断字符串合法性的函数换成一个很简单的正则表达式,list[i].matches("[ASDW]\\d+"),其中[ASDW]表示A或S或D或W,\\d表示数字0-9,+表示前一个类型的字符存在一次或多次,X{n,m}表示X至少n此最多m次
  • String类中的split()方法可以将一个字符串按照给定的模式分隔到一个字符串数组中

猜你喜欢

转载自blog.csdn.net/heyiamcoming/article/details/80396754