java - 用于计算机器人朝向及其坐标值的 Java 程序
问题描述
我有一个 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);
推荐阅读
- c - fgets() 缓冲区中超出边界检查的额外字符会发生什么情况?
- ios - 如何在不禁用列表项命中测试的情况下启用对列表项的选择?
- javascript - 显示模块未找到错误即“无法解析模块@react-native-community/async-storage”,即使已安装模块
- c++ - 使用循环 C++ 遍历向量
- php - 如何通过 Bootstrap 将分页输出到 php?
- google-apps-script - Google App Script Card Service datepicker 返回奇怪的值
- gitlab - gitlab-ci 注册运行器 x509
- liferay - Liferay 7 Web 内容显示 - 全球站点中的 Web 内容不可用
- cakephp-3.0 - Cakephp 3:如何通过其包含的模型限制查询
- javascript - PDFJS:在画布上渲染 PDF