In: Computer Science
5. [20 marks] (TestRobot.java) Design a class named Robot. The Robot class has three private data fields: position x, position y, and the direction number (0 for east, 1 for south, 2 for west, and 3 for north). Assume that positive x points to the east and positive y points to the south, and initially x = 0, y = 0, direction = 0. 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 the robot by calling its methods. For example, for the sample testing above, your program should display x = -20, y = -30, and direction = 2.
The required code & output are shared below:
Java Code:
public class Robot
{
private int x,y;
private int direction;
public void Robot(){
x=0;
y=0;
direction=0;
}
public void Robot(int x1, int y1, int d1){
x= x1;
y= y1;
direction= d1;
}
public int getx(){
return x;
}
public int gety(){
return y;
}
public int get_direction(){
return direction;
}
public void setx(int x1){
x = x1;
}
public void sety(int y1){
y = y1;
}
public void set_direction(int d1){
direction = d1;
}
public void forward(int distance){
if (direction == 0){
x = x + distance;
}
else if (direction == 1){
y = y + distance;
}
else if (direction == 2){
x = x - distance;
}
else if (direction == 3){
y = y - distance;
}
}
public static void main(String[] args) {
Robot r1 = new Robot();
r1.forward(20);
r1.set_direction(3);
r1.forward(30);
r1.set_direction(2);
r1.forward(40);
System.out.println("x = "+r1.getx()+", y = "+r1.gety()+", direction = "+r1.get_direction());
}
}
Output Screenshot:
(*Note: Please up-vote. If any doubt, please let me know in the comments)