4.1k views
4 votes
Rearrange the code to produce a class that keeps and updates total miles driven

When a car drives, the odometer is updated. Use the concept of "keeping a total" to track the total miles driven. Rearrange the following lines to produce a class that keeps and updates such a total. Not all lines are useful.
import java.util.Scanner;
public class Car {
private double odometer;

public Car() {
odometer = 0;
}
public void drive(double miles) {
odometer = odometer + miles;
}
public double getOdometer() {
return odometer;
}
public static void main(String[] args) {
Car car = new Car();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of miles driven: ");
double miles = scanner.nextDouble();
car.drive(miles);
System.out.println("Total miles driven: " + car.getOdometer());
}
}

User Cam Connor
by
7.9k points

1 Answer

4 votes

Final answer:

The code provided is a Java class called Car that correctly tracks the total miles driven. The drive method updates the odometer,

the getOdometer method retrieves the total, and the main method gets user input and displays the total miles driven.

Step-by-step explanation:

The question involves rearranging the provided lines of code to create a Java class called Car that tracks and updates the total miles driven. The class should have an odometer field that is updated whenever the drive method is called.

This method adds the miles driven to the odometer total, which can be retrieved using the getOdometer method. The main method creates an instance of the Car class, takes in the number of miles driven from user input using a Scanner, calls the drive method with the input, and finally, prints out the total miles driven


The provided lines of code are already arranged correctly, and no rearrangement is needed. However, as instructed, you should ignore irrelevant parts of the question such as the reference to using positive and negative numbers to represent different directions of travel.

The focus here is on keeping a total of miles driven, irrespective of direction. The concept of keeping a total relies on accumulation rather than on direction, which would be relevant in a situation where net displacement was the focus.

User Hatesms
by
8.2k points