java-HJ17 坐标移动
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* HJ17 坐标移动
* @author d3y1
*/
public class Main {
public static void main(String[] args) {
solution1();
// solution2();
}
/**
* 字符串
*/
private static void solution1(){
Scanner in = new Scanner(System.in);
String line = in.nextLine().trim();
String[] moves = line.split(";");
int x=0,y=0;
char direct;
int number;
for(String move: moves){
if(isValid(move)){
direct = move.charAt(0);
number = Integer.valueOf(move.substring(1));
switch(direct){
case 'A': {x -= number; break;}
case 'D': {x += number; break;}
case 'W': {y += number; break;}
case 'S': {y -= number; break;}
default: break;
}
}
}
System.out.print(x+","+y);
}
/**
* 校验移动是否合法
* @param move
* @return
*/
private static boolean isValid(String move){
// String regex = "[ADWS]\\d{1}|[ADWS][1-9]\\d{1}";
String regex = "[ADWS][0-9]{1,2}";
if(move.matches(regex)){
return true;
}
return false;
}
/**
* 字符串
*/
private static void solution2(){
Scanner in = new Scanner(System.in);
String line = in.nextLine().trim();
String[] moves = line.split(";");
int x=0,y=0;
char direct;
int number;
for(String move: moves){
if(checkValid(move)){
direct = move.charAt(0);
number = Integer.valueOf(move.substring(1));
switch(direct){
case 'A': {x -= number; break;}
case 'D': {x += number; break;}
case 'W': {y += number; break;}
case 'S': {y -= number; break;}
default: break;
}
}
}
System.out.print(x+","+y);
}
/**
* 校验移动是否合法
* @param move
* @return
*/
private static boolean checkValid(String move){
// String regex = "[ADWS]\\d{1}|[ADWS][1-9]\\d{1}";
String regex = "[ADWS][0-9]{1,2}";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(move);
if(matcher.matches()){
return true;
}
return false;
}
}