首页 > 解决方案 > 用于计算机器人朝向及其坐标值的 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);
    }

}

标签: javaarrays

解决方案


这个你可能想多了。

你面对的最终方向只是你做出的最后一步。例如,无论您采取什么行动,如果您还剩下最后一步,您的机器人总是面向西方。

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);

推荐阅读