Java Program Implement a class Robot that simulates a robot wandering on an infi
ID: 3883150 • Letter: J
Question
Java Program
Implement a class Robot that simulates a robot wandering on an infinite plane.
The robot is located at a Point with integer coordinates and faces north, east, south, or west.
Supply methods:
public void turnLeft(),
public void turnRight(),
public void move(),
public Point getLocation(),
public String getDirection().
The turnLeft() and turnRight() methods change the direction but not the location.
The move method() moves the robot by one unit in the direction it is facing.
The getDirection method() returns a string "N", "E", "S", or "W"
You will need to create two or three robots and use them to test each of the different methods.
Make sure you have a default constructor,
and have overridden the toString() method.
Make sure you display the position of the robot at the least everytime you move it.
Remember not to do any reading/writing in the Robot class itself
Explanation / Answer
Code:
public class Robot {
private String direction;
private Point location;
public Robot() {
direction="N";
location=new Point(0, 0);
}
public void turnLeft(){
if(direction.contentEquals("N")){
direction="W";
}else if(direction.contentEquals("W")){
direction="S";
}else if(direction.contentEquals("S")){
direction="E";
}else if(direction.contentEquals("E")){
direction="N";
}
}
public void turnRight(){
if(direction.contentEquals("N")){
direction="E";
}else if(direction.contentEquals("W")){
direction="N";
}else if(direction.contentEquals("S")){
direction="W";
}else if(direction.contentEquals("E")){
direction="S";
}
}
public void move(){
if(direction.contentEquals("N")){
location.y=location.y+1;
}else if(direction.contentEquals("W")){
location.x=location.x-1;
}else if(direction.contentEquals("S")){
location.y=location.y-1;
}else if(direction.contentEquals("E")){
location.x=location.x+1;
}
}
public String getDirection() {
return direction;
}
public Point getLocation() {
return location;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.