一开始理所当然用正则matcher.group()匹配出字母后面的数字,提交时候发现不能使用正则Matcher和Pattern
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main{
private static final String reg = "\\d+$";
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
Pattern pattern = Pattern.compile(reg);
String operate = sc.nextLine();
String[] splits = operate.split(";");
int x = 0;
int y = 0;
for (int i = 0; i < splits.length; i++) {
String op = splits[i];
Matcher matcher = pattern.matcher(op);
// 限制
if (op.length() > 3 || op.length() < 2 || !matcher.find()
|| !op.startsWith("A") && !op.startsWith("S") && !op.startsWith("D") && !op.startsWith("W")){
continue;
}
int moveNum = Integer.parseInt(matcher.group());
if (op.startsWith("A")){
x = x - moveNum;
} else if (op.startsWith("D")){
x = x + moveNum;
} else if (op.startsWith("W")){
y = y + moveNum;
} else if (op.startsWith("S")){
y = y - moveNum;
}
}
System.out.println(x+","+y);
}
}
转变思路,根据;截取,再把每一段分解为char[]数组,长度不能超过3,第一个必须是ASDW方向,后面必须是数字,char必须>=0 和 <=9,然后拼接起来,然后变成数字类型进行±操作
import java.util.*;
public class Main{
private static final String reg = "\\d+$";
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String operate = sc.nextLine();
String[] splits = operate.split(";");
int x = 0;
int y = 0;
for (int i = 0; i < splits.length; i++) {
String op = splits[i];
char[] chars = op.toCharArray();
if (chars.length>3 || chars.length<2){
continue;
}
// 先把第一个字符截取出来
String direction = String.valueOf(chars[0]);
if (!"ASDW".contains(direction)){
continue;
}
// 把移动步数截取出来,同时判断是否数字
String move = "";
for (int j = 1; j < chars.length; j++) {
char num = chars[j];
if (num<'0' || num>'9'){
move = "";
break;
} else {
move = move + num;
}
}
if (!move.equals("")){
int moveNum = Integer.parseInt(move);
if (direction.equals("A")){
x = x - moveNum;
} else if (direction.equals("D")){
x = x + moveNum;
} else if (direction.equals("W")){
y = y + moveNum;
} else if (direction.equals("S")){
y = y - moveNum;
}
}
}
System.out.println(x+","+y);
}
}