Created
February 4, 2021 15:18
-
-
Save gitaficionado/54b4861a9306455729ead0b9e0ebb994 to your computer and use it in GitHub Desktop.
Create a class named Vehicle that simulates a car moving along a 40 block stretch of road. Your class will build a vehicle and keep track of its location on the road. Location values may range from -20 to 20. A location value of 0 represents block 0, a location value of 1 represents block 1, a location value of 2 represents block 2, etc. If the …
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Vehicle | |
{ | |
//private integer to store the vehicle's location | |
private int __________; | |
public ________() | |
{ | |
location = ___; | |
} | |
public Vehicle (int ____) | |
{ | |
//Call default constructor setting location to 0 | |
this(); | |
//Check value loc and update location if this is valid | |
if (loc >= -___ && loc <= __) | |
_________ = loc; | |
} | |
public String toString () | |
{ | |
//Create a variable to store our output | |
________ out = ""; | |
//Calculate the distance of the car from the left of the screen, | |
//then use a for loop to add this many spaces to our output | |
int dist = 20 + location; | |
for (int i = ___; i <= ______; i++) | |
out += " "; | |
//End the output with a @ to symbolize our car, | |
//then return the string. | |
out += "@"; | |
return _____; | |
} | |
int getLocation () | |
{ | |
//A getter method for accessing the private variable, location | |
_______ location; | |
} | |
/* | |
* Altering the vehicle's location is done using forward and backward | |
* methods. When combined with private variables, this allows us to | |
* control how vehicles can be moved by other classes. There is no | |
* setLocation() method because the vehicle we are modelling is | |
* incapable of teleportation. | |
*/ | |
void backward() | |
{ | |
if (location > -20) | |
_____________ --; | |
} | |
void forward() | |
{ | |
if (location < ___) | |
_________++; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment