(1) Create two files: Car.java - Class definition, object class CarTester.java - Driver program, contains main() method Build the Car class with the following specifications:
(1) Create two files:
- Car.java - Class definition, object class
- CarTester.java - Driver
program , contains main() method
Build the Car class with the following specifications:
-
Private fields:
String make - Initialized in default constructor to "none"
int mileage - Initialized in default constructor to 0 -
Constructors:
Default constructor with no parameter
Overloaded constructor with two parameters -
Methods:
setMake() & getMake()
setMileage() & getMileage()
(2) In your testing class, prompt the user for information to create two car objects of the Car class. Remember that the car make could contain multiple words, such as "Land Rover". Think about which method you should use in order to read in the car make information (nextLine() or next()?).
A possible problem: you might notice that your nextLine() method does not read in anything when it is called after next() or nextInt() method. To fix this, you need to call an empty scan.nextLine(); to be able to read in the user's input when nextLine() and nextInt() are called in sequence.
Ex:
Car 1
Enter the car make:
Land Rover
Enter the car mileage:
100
Car 2
Enter the car make:
Ford
Enter the car mileage:
150000
(3) Add toString method to Car class that returns the information of the object as a string. When you print the car1 object in main(), you will get the following output.
Ex:
The make of the car is Land Rover, and the mileage of the car is 100.
(4) Add computeMPG method to the Car class that returns the MPG (miles per gallon) value as a double. The method should accept two parameters, one is called miles and the other is called gallons, which indicates how many gallons of gas has been used after driving those miles. Both should be int type. Set the output to 3 decimal places.
For example, when you call this method in main() for car1 with miles = 200 and gallons = 6 as actual parameters, you will get the following output.
Ex:
The MPG of your Land Rover is 33.333.
Trending now
This is a popular solution!
Step by step
Solved in 2 steps with 1 images