模拟机器人行走
某少年宫引进了一批机器人小车。可以接受预先输入的指令,按指令行动。小车的基本动作很简单,只有3种:左转(记为L),右转(记为R),向前走若干厘米(直接记数字)。
例如,我们可以对小车输入如下的指令:15L10R5LRR10R20 则,小车先直行15厘米,左转,再走10厘米,再右转,…
不难看出,对于此指令串,小车又回到了出发地。
你的任务是:编写程序,由用户输入指令,程序输出每条指令执行后小车位置与指令执行前小车位置的直线距离。
输入、输出格式要求
用户先输入一个整数n(n<100),表示接下来将有n条指令。接下来输入n条指令。每条指令只由L、R和数字组成(数字是0~100之间的整数),每条指令的长度不超过256个字符。
程序则输出n行结果。每条结果表示小车执行相应的指令前后位置的直线距离。要求四舍五入到小数后2位。 例如:用户输入:
5
L100R50R10
3LLL5RR4L12
LL
100R
5L5L5L5
则程序输出:
102.96
9.06
0.00
100.00
0.00
解:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
String[] haha = new String[num];
for (int i = 0; i < num; i++) {
char[] strdata = (sc.next()).toCharArray();// 原始String数据
List<String> listdata = new ArrayList<String>();// 处理之后的数据
String ju = "";// 记录数字
for (int ss = 0; ss < strdata.length; ss++) {
if (strdata[ss] == 'L' || strdata[ss] == 'R') {
if (!ju.equals("")) {
listdata.add(ju);
ju = "";
}
listdata.add(String.valueOf(strdata[ss]));
} else ju += strdata[ss];
}
// 最后的距离
if (!ju.equals("")) listdata.add(ju);
haha[i] = new java.text.DecimalFormat("#0.00").format(xx(listdata));
}
// 输出
for (int i = 0; i < num; i++) {
System.out.println(haha[i]);
}
}
// 计算路程
public static double xx(List<String> listdata) {
int f = 0, jj,x = 0, y = 0;
for (int i = 0; i < listdata.size(); i++) {
if (listdata.get(i).equals("L")) {
f--;
if (f < 0)f = 3;
} else if (listdata.get(i).equals("R")) {
f++;
if (f > 3)f = 0;
} else {
jj = Integer.parseInt(listdata.get(i));
switch (f) {
case 0:
y += jj;
break;
case 1:
x += jj;
break;
case 2:
y -= jj;
break;
case 3:
x -= jj;
break;
default:
break;
}
}
}
return Math.sqrt(Math.pow(x,2) + Math.pow(y,2));
}