LRUD分别表示左右上下,后面跟行驶距离,计算到原点的距离?
package 测试包;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class 小车行驶距离简化 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入字符串如:LL10UU20L20U20U");
String s = sc.nextLine();
sc.close();
Pattern p = Pattern.compile("[A-z][0-9]+");//正则表达式匹配有效的命令
Matcher m = p.matcher(s);
ArrayList<String> al = new ArrayList<String>();
while (m.find()) {
al.add(m.group());
}
int x = 0;
int y = 0;
for (int i = 0; i < al.size(); i++) {
switch (al.get(i).charAt(0)) {
case 'L':
x = x
- Integer.parseInt(al.get(i).substring(1,
al.get(i).length()));
break;
case 'R':
x = x
+ Integer.parseInt(al.get(i).substring(1,
al.get(i).length()));
break;
case 'U':
y = y
- Integer.parseInt(al.get(i).substring(1,
al.get(i).length()));
break;
case 'D':
y = y
- Integer.parseInt(al.get(i).substring(1,
al.get(i).length()));
break;
default:
break;
}
}
System.out.println("有效的行驶指令是:" + al);
System.out.println("小车的停止位置是:[" + x + "," + y + "]");
System.out.println("行驶的距离是:"
+ Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)));
// LL10UU20L20U20U
}
}
输入:
LL10UU20L20U20U
输出:
请输入字符串如:LL10UU20L20U20U
LL10UU20L20U20U
有效的行驶指令是:[L10, U20, L20, U20]
小车的停止位置是:[-30,-40]
行驶的距离是:50.0