In: Computer Science
[20 marks] (TestRobot.java) 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.
Program Code [JAVA]
// Robot class
class Robot {
// Required data fields
private int position_x;
private int position_y;
private String direction;
// no-arg constructor
public Robot() {
this.position_x = 0;
this.position_y = 0;
direction = "east";
}
// Parameterized constructor
public Robot(int position_x, int position_y, String direction) {
this.position_x = position_x;
this.position_y = position_y;
this.direction = direction;
}
// Accessors & Mutators
public int getPosition_x() {
return position_x;
}
public void setPosition_x(int position_x) {
this.position_x = position_x;
}
public int getPosition_y() {
return position_y;
}
public void setPosition_y(int position_y) {
this.position_y = position_y;
}
public String getDirection() {
return direction;
}
public void setDirection(String direction) {
this.direction = direction;
}
// forward method
public void forward(int pixels) {
// Checking for each direction
if (direction.equalsIgnoreCase("east"))
position_x += pixels;
else if(direction.equalsIgnoreCase("west"))
position_x -= pixels;
else if(direction.equalsIgnoreCase("south"))
position_y += pixels;
else if(direction.equalsIgnoreCase("north"))
position_y -= pixels;
}
}
public class TestRobot {
// main method
public static void main(String[] args) {
// Creating a Robot object
Robot robot = new Robot();
// Moving as stated in statement
robot.setDirection("east");
robot.forward(20);
robot.setDirection("north");
robot.forward(30);
robot.setDirection("west");
robot.forward(40);
// Now printing final values of x, y and direction
System.out.println("x = " + robot.getPosition_x() + ", y = " + robot.getPosition_y() +
", and direction = " + robot.getDirection());
}
}
Sample Output:-
----------------------------------------------------------------------
COMMENT DOWN FOR ANY QUERIES!!!
HIT A THUMBS UP IF YOU DO LIKE IT!!!