Objective:
Add a method to calculate the amount of fuel needed to travel a given distance.
Definition of the fuelneeded( ) Method
Name: fuelneeded
Return Type: double
Parameter: int miles (number of miles to travel)
Description: Calculates the amount of fuel needed to cover the specified distance.
Implementation:
double fuelneeded(int miles) { return (double) miles / mpg; }
Note: The returned value is of type double to deal with fractional fuel values.
Vehicle Class with fuelneeded( ) Method
Fields:
int passengers: Number of passengers.
int fuelcap: Fuel storage capacity in gallons.
int mpg: Fuel consumption in miles per gallon.
Methods:
int range(): Returns the vehicle's range.
double fuelneeded(int miles): Calculates the fuel needed for a given distance.
Code Example:
class Vehicle { int passengers; // número de passageiros int fuelcap; // capacidade de armazenamento de combustível em galões int mpg; // consumo de combustível em milhas por galão // Retorna a autonomia. int range() { return mpg * fuelcap; } // Calcula o combustível necessário para cobrir uma determinada distância. double fuelneeded(int miles) { return (double) miles / mpg; } }
Usage Example: CompFuel Class
Objective: Demonstrate the use of the fuelneeded( ).
method
Code Example:
class CompFuel { public static void main(String args[]) { Vehicle minivan = new Vehicle(); Vehicle sportscar = new Vehicle(); double gallons; int dist = 252; // Atribui valores a campos de minivan minivan.passengers = 7; minivan.fuelcap = 16; minivan.mpg = 21; // Atribui valores a campos de sportscar sportscar.passengers = 2; sportscar.fuelcap = 14; sportscar.mpg = 12; gallons = minivan.fuelneeded(dist); System.out.println("To go " + dist + " miles minivan needs " + gallons + " gallons of fuel."); gallons = sportscar.fuelneeded(dist); System.out.println("To go " + dist + " miles sportscar needs " + gallons + " gallons of fuel."); } }
Program Operation
This example demonstrates how to use parameterized methods to add specific functionality to a class, in this case calculating the fuel needed for a trip.
The above is the detailed content of Adding a parameterized method to Vehicle. For more information, please follow other related articles on the PHP Chinese website!