gpt4 book ai didi

Java程序计算机器人朝向及其坐标值

转载 作者:行者123 更新时间:2023-11-30 12:01:55 26 4
gpt4 key购买 nike

我有一个 5*5 矩阵,最初机器人位于面向北方的坐标 (2,2) 处。机器人向左、右、上、下、左方向移动。我必须计算机器人运动后的坐标 (LRUDL) 及其最终朝向。

下面是我试过的代码,但我无法在其中获取机器人方向。如果有人可以帮助我,那就太好了

在此输入验证码

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class FinalPosition {

public static void main(String[] args) throws NumberFormatException, IOException {

BufferedReader br1=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the moving direction:");
String move = br1.readLine();
//String move = "LRUDL";
position(move);

}

private static void position(String move) throws NumberFormatException, IOException {

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the X axis co ordinates:");
int xaxis = Integer.parseInt(br.readLine());
System.out.println("Enter the Y axis co ordinates:");
int yaxis = Integer.parseInt(br.readLine());
System.out.println("Enter the initial direction of the robot");
String direction = br.readLine();

int l = move.length();
int countUp = 0, countDown = 0;
int countLeft = 0, countRight = 0;
int x =0;
int y= 0;
int count= 0;

char [] c=move.toCharArray();
System.out.println(c);

for(int i=0; i< c.length; i++) {

if(c[i]== 'U')
countUp++;
else if (c[i] == 'D')
countDown++;
else if (c[i] == 'L')
countLeft++;
else if (c[i] == 'R')
countRight++;
else
count = 0;
}

if(countRight >= countLeft){
x = (countRight - countLeft);
} else {
x = (countLeft - countRight);
}

if(countUp >= countDown ){
y = (countUp - countDown);
} else {
y = (countDown - countUp);
}

System.out.println("X AXIS IS"+ x + " Y AXIS IS "+ y);
System.out.println("xaxis "+ xaxis + " yaxis "+ yaxis);
int finalXaxisPosition = xaxis - x;
int finalYaxisPosition = yaxis - y;
System.out.println("Final Position: "+ finalXaxisPosition + "," + finalYaxisPosition);
}

}

最佳答案

你可能想多了。

你面对的最终方向就是你最后的一步。例如,无论您采取什么行动,如果您的最后一步是左移,您的机器人将始终面向西方。

String direction = "";
int lastIndex = move.length - 1;
switch(c[lastIndex]) {
case 'L': direction = "West"; break;
case 'U': direction = "North"; break;
case 'D': direction = "South"; break;
case 'R': direction = "East"; break;
default: throw new IllegalArgumentException("Cannot accept movement " + c[lastIndex]);
}
System.out.println("Final Direction: " + direction);

关于Java程序计算机器人朝向及其坐标值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59162987/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com