In: Computer Science
Design a class named Robot. The Robot class has three private data fields: position x, position y, and the direction (east, south, west, and north). Assume that positive x points to the east and positive y points to the south, and initially x = 0, y = 0, direction = "east".
Create a no-arg constructor and another constructor which sets the three data fields. Create the accessors and mutators for the three data fields.
Create a method named forward that moves the robot along the current direction for the given distance. For example, if the robot is currently facing east, forward(10) will move the robot along the positive x direction for 10 pixels.
In the main method, create a Robot object, move it to the east for 20 pixels, then set the direction to north and move 30 pixels, and finally set the direction to west and move 40 pixels. Find and display the final x and y values and the direction of robot by calling its methods. For example, for the sample testing above, your program should display x = -20, y = -30, and direction = west.
Please find the answer below.
Please do comments in case of any issue. Also, don't forget to rate
the question. Thank You So Much.
Robot.java
package c14;
public class Robot {
private int x;
private int y;
private String direction;
public Robot() {
this.x = 0;
this.y = 0;
this.direction = "east";
}
public Robot(int x, int y, String direction) {
super();
this.x = x;
this.y = y;
this.direction = direction;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public String getDirection() {
return direction;
}
public void setDirection(String direction) {
this.direction = direction;
}
void forward(int delta) {
if(direction.equals("east"))
{
x+=delta;
}else if(direction.equals("west"))
{
x-=delta;
}else if(direction.equals("north"))
{
y-=delta;
}else if(direction.equals("south"))
{
y+=delta;
}
}
public static void main(String[] args) {
Robot robot = new Robot();
robot.forward(20);
robot.setDirection("north");
robot.forward(30);
robot.setDirection("west");
robot.forward(40);
System.out.println("Final x is :
"+robot.getX());
System.out.println("Final y is :
"+robot.getY());
System.out.println("Final direction
is : "+robot.getDirection());
}
}