题目:
开发一个坐标计算工具, A表示向左移动,D表示向右移动,
W表示向上移动,S表示向下移动。从(0,0)点开始移动,
从输入字符串里面读取一些坐标,并将最终输入结果输出到输出文件里面。
输入:
合法坐标为A(或者D或者W或者S) + 数字(两位以内)
坐标之间以;分隔。
非法坐标点需要进行丢弃。如AA10; A1A; $%$; YAD; 等。
输入描述:
一行字符串
输出描述:
最终坐标,以,分隔
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
//x,y坐标
int x = 0, y = 0;
String s = in.nextLine();
//用“;”分割字符串
String[] str = s.split(";");
for (String s1 : str) {
//遍历字符串,按要求进行对比
if (s1.charAt(0) == 'A' && s1.substring(1).matches("[0-9]{1,2}")) {
//将字符转换成整数
x -= Integer.parseInt(s1.substring(1));
} else if (s1.charAt(0) == 'D' && s1.substring(1).matches("[0-9]{1,2}")) {
x += Integer.parseInt(s1.substring(1));
} else if (s1.charAt(0) == 'W' && s1.substring(1).matches("[0-9]{1,2}")) {
y += Integer.parseInt(s1.substring(1));
} else if (s1.charAt(0) == 'S' && s1.substring(1).matches("[0-9]{1,2}")) {
y -= Integer.parseInt(s1.substring(1));
}
}
System.out.println(x + "," + y);
}
}
}