Java 1. write a java program with Class called Vehicle which includes the follow
ID: 3594430 • Letter: J
Question
Java
1. write a java program with Class called Vehicle which includes the following:
3 instance variables Color (String), TankCapacity, range (intergers) (all private)
Constructor to initialize these vairables.
Get methods to return the 3 instance variables
Public method to return mpg (miles per gallom - divide range/TankCapacity)
Run the class with a TestVehicle main class which creates 2 objects:
Prius: with the following properties: Color white, TankCapacity: 12 gallons, range 600 miles.
FordRanger: with the following properties: Color blue, TankCapacity: 15 gallons, range 400 miles.
Note: Use the constructor to set the above properties
Run the program and use printf to out put as below
Prius Color: White Tank Capacity: 12 Range: 600 mpg: 50
Ford Ranger Color: Green Tank Capacity: 15 Range: 400 mpg: 26
2. Modify above the program by adding set methods to set the instance vairables by propting the user to enter values from Key board.
I only need the answer to 2
Explanation / Answer
import java.util.*;
class Vehicle {
private String Color;
private int TankCapacity;
private int range;
public Vehicle(String c, int Tc, int r) {
Color = c;
TankCapacity = Tc;
range = r;
}
//getter functions
public String getColor() {
return Color;
}
public int getTankCapacity() {
return TankCapacity;
}
public int getRange() {
return range;
}
//mpg function
public int getMilesPerGallon() {
return range / TankCapacity;
}
//setter functions ----> This is for part 2
public void setColor(String c) {
Color = c;
}
public void setTankCapacity(int tc) {
TankCapacity = tc;
}
public void setRange(int r) {
range = r;
}
}
public class TestVehicle {
public static void main(String[] args) {
//For Part 1
Vehicle obj1 = new Vehicle("white", 12, 600);
Vehicle obj2 = new Vehicle("blue", 15, 400);
System.out.println("Prius Color: " + obj1.getColor() + " Tank Capacity: " + obj1.getTankCapacity() + " Range: " + obj1.getRange() + " mpg: " + obj1.getMilesPerGallon());
System.out.println("Prius Color: " + obj2.getColor() + " Tank Capacity: " + obj2.getTankCapacity() + " Range: " + obj2.getRange() + " mpg: " + obj2.getMilesPerGallon());
//get input from user and set value using setter function -> For part 2
Scanner sc = new Scanner(System.in);
System.out.println("Enter new color for Prius");
String newColor = sc.next();
obj1.setColor(newColor);
System.out.println("New color for Prius by user is : " + obj1.getColor());
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.