~~~Update: Solved! Thanks everyone!~~~
I’m working on a project from the Blue Pelican Java book, lesson 16 project Gas Mileage. It asks to create two classes, one is Automobile which holds the methods I will work with. The other class, Tester, is the main class. Every time I run the Tester class, it returns a value of -Infinity. I can’t figure out why, other than that I’ve singled out the problem is in the Automobile class at line 14 in the takeTrip method. When I leave that method out of the Tester class, it returns the correct values.
This is the Automobile class:
public class Automobile
{
public Automobile(double m) // Accepts value m to the double mpg. Also declares
{
double mpg = m;
double gallons;
}
public void fillUp(double f) // Adds fuel to the tank
{
gallons += f;
}
public void takeTrip(double t) // Takes away fuel from the tank depending upon how many miles are driven
{
gallons -= t / mpg; // Not sure how to do this line. For some reason, when I reference mpg, the output of Tester is "-infinity". Shouldn't it do gallons = gallons - (miles driven / mpg)?
}
public double reportFuel() // Returns value of how much fuel is left in tank
{
double r = gallons;
return r;
}
public double mpg;
public double gallons;
}
And this is the Tester class:
public class Tester
{
public static void main(String args[])
{
Automobile myBmw = new Automobile(24); // Passes constructor argument of 24 mpg
myBmw.fillUp(20); // Adds 20 gallons to fillUp method
myBmw.takeTrip(100); // Takes away the fuel used for 100 miles using the takeTrip method
double fuel_left = myBmw.reportFuel(); // Initializes fuel_left to the method reportFuel
System.out.println(fuel_left);
}
}
Any help is appreciated, thanks!
-AJ
You constructor doesn’t need the ‘double’ identifier. Here you are creating a new variable also called mpg, which is forgotten after the constructor completes. Instead use this: