go to previous page   go to home page   go to next page

Could a main() method create a Car object?

Answer:

Sure, as long as it has access to the class definition.


Using a Car Object

Look at the parameter list for the constructor:

Car( double startOdo, double endingOdo, double gallons );

This says that the constructor must be called with three double precision values.

User interaction in the following is similar to previous programs. All input values are double precision.


import java.util.Scanner ;

class MilesPerGallon
{
  public static void main( String[] args ) 
  {
    Scanner scan = new Scanner(System.in);

    double startMiles, endMiles, gallons;

    System.out.print("Enter first reading: " ); 
    startMiles = scan.nextDouble();

    System.out.print("Enter second reading: " ); 
    endMiles = scan.nextDouble();

    System.out.print("Enter gallons: " ); 
    gallons  = scan.nextDouble();

    Car car = new Car( , ,   );

    System.out.println( "Miles per gallon is "  + car.calculateMPG() );
  }
}

If Car.java contains the definition of the Car class and MilesPerGallon.java contains the above program and both are in the same disk directory, then the program could be compiled and run by doing:

C:\SomeDirectory>javac MilesPerGallon.java
C:\SomeDirectory>java  MilesPerGallon

But first more work needs to be done.



QUESTION 3:

Fill in the blanks so that the Car constructor uses data from the user.