javaodometer

Finding differences of numbers in a for loop


I'm a beginner at java and was wondering on how to find the maximum difference between numbers inputted into a for loop. My program takes x amount of odometer readings (Between consecutive trips) from a car, e.g 100km, 150km, 400km, and is supposed to take the maximum distance traveled for all trips, which in this example would be 250km, as well as the minimum which would be 50km and average distance traveled between each odometer reading.

So far i've only managed to find a way to calculate the biggest value and smallest value for each odometer reading, given by the variables maximum and minimum, however have no idea on how to approach or begin to program finding the difference between trips. I tried implementing an array of some sort (not shown in this code) but i keep receiving too many errors. I could really use some advice on how to approach this problem or some insight; it would be greatly appreciated. Thank you for your time.

System.out.print("Input number of trips: ");    
carSample.numberOfTrips = input.nextInt();


    int maximum = Integer.MIN_VALUE;
    int minimum = Integer.MAX_VALUE;
    int total = 0;

for (int i = 0; i < carSample.numberOfTrips; i++) {
    System.out.print("Odometer reading " + (i + 1) + ": ");
    int odometerReading = input.nextInt();
    total += odometerReading;
    if (odometerReading > maximum){
        maximum = odometerReading;
        }
    if (odometerReading < minimum){
        minimum = odometerReading;  
    }

Solution

  • int previous = 0;
    int minimumTrip = Integer.MAX_VALUE;
    int maximumTrip = Integer.MIN_VALUE;
    
    for (int i = 0; i < carSample.numberOfTrips; i++) {
        System.out.print("Odometer reading " + (i + 1) + ": ");
        int odometerReading = input.nextInt();
        int currentTrip = odometerReading - previous;
        if (currentTrip > maximumTrip){
            maximumTrip = currentTrip;
            }
        if (currentTrip < minimumTrip){
            minimumTrip = currentTrip;  
        }
        previous = odometerReading;
    }
    

    If reading starts not from 0 consider previous = first odometer reading