Lab 22
Introduction
The goal for this activity is to implement a Car
class so that it conforms to the UML below:
Part 1: Driver, Constructor and toString
- Create two Java class files: CarTester.java and Car.java. Only CarTester.java should include a main method.
- Add the three instance variables from the UML diagram to your
Car
class. - Code the constructor for your
Car
class. This should intialize themake
andyear
fields using the arguments to the constructor. Thespeed
should be initialized to 0. - Code the
toString
method. This method should take no parameters and should return a string generated using theString.format
method:String.format("A %d %s that is going %.1f mph", year, make, speed)
- Test your partially completed
Car
class by adding code to themain
in CarTester.java that creates and prints two car objects. The contents ofmain
should look something like the following.Car car1; Car car2; car1 = new Car("Ford", 1997); car2 = new Car("Toyota", 2014); System.out.println(car1.toString()); System.out.println(car2.toString());
Part 2: Remaining Methods
Complete each of the remaining methods of the Car
class. Test each method by adding appropriate calls to main
.
- The three "getter" methods should each return the value of the appropriate instance variable.
- The
accelerate
method should increase the current speed of the car by 5.0 mph. It should NOT be possible to increase the speed beyond 150.0 mph. If a call toaccelerate
would push the speed beyond 150.0, the speed should be set to 150.0.
(How will you test that this is working correctly? How many times do you need to callaccelerate
before the upper speed limit is reached? Might a loop be helpful here?) - The
brake
method should decrease the current speed by 5.0 mph. It should not be possible for the speed to drop below 0 mph.
Submit Car.java through AutoLab by the end of the day. AutoLab will not run Checkstyle tests on your submission. Here are the AutoLab tests in case you want to test locally before submitting CarTest.java
Part 3: Viewing Variables - JGrasp Viewer Canvas (optional)
Use the "viewer canvas" feature of JGrasp to run your main method interactively: Instead of clicking on the button, click on
. This should allow you to step through your main one instruction at a time. You should be able to inspect the contents of your variables by dragging them from the "Variables" tab into the viewer canvas window.
To see your variables in Eclipse, you would need to run the Debugger. If you are interested, check out Norm Krumpe's Debugger Tutorial (~15 min) which covers basic vocabulary and explains how to track variables in different areas in the Eclipse screen.
Acknowledgements
Thank you to Dr. Sprague for this activity.