Reputation: 13
I have an assignment to write a class with a constructor + various methods that returns values to the main class.
My code never compiles correctly either due to error:cannot find simple or illegal start of expression.
I believe I'm fundamentally misunderstanding how to make a constructor, what exactly the main method is, and how one class calls another.
Assignment:
Suppose that you are given the following Driver class, which includes a main method:
public class Driver {
public static void main(String[] args) {
double distance = 400.48;
double fuel = 21.4;
AutoTrip myTrip = new AutoTrip(distance, fuel);
System.out.print("My car traveled " + myTrip.getDistance() + " miles");
System.out.println("on " + myTrip.getFuel() + " gallons of gasoline.");
double mileage = myTrip.getMPG(); // get miles per gallon
System.out.println("My mileage was " + mileage + ".");
}
}
*Now suppose that executing main produces the following output: My car traveled 400.48 miles on 21.4 gallons of gasoline.
My mileage was 18.714018691588787.
Implement the AutoTrip class so that it produces the indicated output.*
My code:
public class AutoTrip {
public AutoTrip(double distance, double fuel){
this.distance = distance;
this.fuel = fuel;
}
public double getDistance(){
return distance;
}
public double getFuel(){
return fuel;
}
public double getMPG(){
return distance / fuel;
}
}
Upvotes: 1
Views: 954
Reputation: 2598
You are forgetting to add your variables in your class AutoTrip
public class AutoTrip {
private double distance; // Missing var
private double fuel; // Missing var
public AutoTrip(double distance, double fuel) {
this.distance = distance;
this.fuel = fuel;
}
public double getDistance() {
return distance;
}
public double getFuel() {
return fuel;
}
public double getMPG() {
return distance / fuel;
}
}
Upvotes: 6