In Java, define classes Step and Directions that satisfy the following propertie
ID: 3782790 • Letter: I
Question
In Java, define classes Step and Directions that satisfy the following properties. All instance variables (in other words, “fields”) should be private or protected.
Step includes:
a direction : can be “right”, “left” or “u-turn”
a road, like: “Mission Blvd” or “Decoto Rd”
a constructor to initialize these values
a toString() method that returns text for the step depending on the direction
for “right”, return “Turn right onto <value of road>”. Assuming the road = “Mission Blvd”, this would be “Turn right onto Mission Blvd”
for “left”, return “Turn left onto <value of road>”
for “u-turn”, return “Make a U-turn, when possible” (ignores value of road)
for anything else, return “Invalid direction : <value of direction>“
Directions includes:
a list of the Step's for this Directions
a constructor to initialize this list
a method to add a Step to the Directions
a method to display the steps to the console output
Explanation / Answer
Hi, Please find my implementation.
Please let me know in case of any issue.
############### Step.java ###############
public class Step {
// instance variables
private String direction;
private String road;
public Step(String direction, String road) {
this.direction = direction;
this.road = road;
}
@Override
public String toString() {
String str = "";
if(direction.equalsIgnoreCase("right") || direction.equalsIgnoreCase("left"))
str = "Turn "+direction+" onto "+road;
else if(direction.equalsIgnoreCase("u-turn"))
str = "Make a U-turn, when possible";
else
str = "Invalid direction: "+direction;
return str;
}
}
############ Directions.java #################
import java.util.ArrayList;
public class Directions {
private ArrayList<Step> directios;
// constructor to initialize directions with empty list
public Directions(){
directios = new ArrayList<>();
}
public void addStep(Step step){
directios.add(step);
}
public void display(){
for(Step step : directios){
System.out.println(step);
}
}
}
############### TestDirection.java ##################
public class TestDirection {
public static void main(String[] args) {
Directions directions = new Directions();
Step step1 = new Step("right", "Mission Blvd");
Step step2 = new Step("u-turn", "Mission Blvd");
Step step3 = new Step("right", "Decoto Rd");
Step step4 = new Step("lift", "Mission Blvd");
Step step5 = new Step("up", "Mission Blvd");
directions.addStep(step1);
directions.addStep(step2);
directions.addStep(step3);
directions.addStep(step4);
directions.addStep(step5);
directions.display();
}
}
/*
Sample run:
Turn right onto Mission Blvd
Make a U-turn, when possible
Turn right onto Decoto Rd
Invalid direction: lift
Invalid direction: up
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.