Using a Car Object

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
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

To see if the design for Car is what you want, use it in a program. If Car is designed well, writing the program should be easy.

import java.util.Scanner ;
import Car;

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() );
  }
}

User interaction is done just as in previous programs. All input values are double precision.

QUESTION 3:

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