我要创建一个模仿机器人功能的代码。转动和移动等等。我觉得好像我以所有错误的方式接近这个......当我写这篇文章时,我以为我理解了它的要点,如果构造函数中的方向是这个,那么如果它转向新的方向就是这个。我对此进行了测试,当然我最终得到了一些真正不正确的结果。我绝对确定我实际上并没有为我的对象使用任何这些函数。我可以获得有关如何使用此类代码的提示吗?
import java.awt.Point;
public class Robot
{
private int x;
private int y;
private int d;
private int p;
public static final int NORTH = 0;
public static final int SOUTH = 1;
public static final int EAST = 2;
public static final int WEST = 3;
/**
* Constructor for objects of class Robot
* @param theX the x coordinate
* @param theY the y coordinate
* @param theDirection the direction the robot is facing
*/
public Robot(int theX, int theY, int theDirection)
{
x = theX;
y = theY;
d = theDirection;
}
public void turnLeft()
{
if(d == NORTH) {
d = WEST;
}
if(d == WEST) {
d = SOUTH;
}
if(d == SOUTH) {
d = EAST;
}
if(d == EAST) {
d = NORTH;
}
}
public String getDirection()
{
if(d == NORTH) {
return "N";
}
if(d == SOUTH) {
return "S";
}
if(d == WEST) {
return "W";
}
if(d == EAST) {
return "E";
}
return "";
}
}
测试
Robot rob = new Robot(20, 20, Robot.SOUTH);
rob.turnLeft;
System.out.println(rob.getDirection);
当我认为它实际上应该返回 E 时,它返回 S。