Search code examples
javaintboolean

How do I create a for loop where i = 0


I'm a beginner at java and I'm facing a very basic problem that I just can't seem to figure out. Any insight or feedback will be greatly appreciated. My program takes user input of the number of trips a car has undergone, and each odometer reading between each trip then calculates the longest, shortest and average distance traveled between each trip.

So far, it works OK besides when there is a test case where the user inputs 0 number of trips, which should output 0 for all calculations (shortest, longest average) but i get the max integer value for each output (2 billion).

I've tried to create a loop that accepts if the number of trips does = 0, then a message is outputted "there is no trips" however I keep receiving this error:

TestCar.java:20: error: incompatible types: int cannot be converted to Boolean
for (int i = 0; i = carSample.numberOfTrips; i++) {

Any help would be greatly appreciated, thank you for your time. Here is my code:

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

    for (int i = 0; i = carSample.numberOfTrips; i++) {
    System.out.print("There are no trips");
    }

    int previous = 0;
    int minimumTrip = Integer.MAX_VALUE;
    int maximumTrip = Integer.MIN_VALUE;
    System.out.print("Odometer reading 0: " );
    carSample.odometerReading = input.nextInt();
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;

Solution

  • It's a simple matter of branching based on user input. There's no reason to run a for loop zero times. Here's the logic behind it (you can write the actual code yourself):

    if numTrips == 0
        print error message
    else
        for numTrips
            blah blah all your logic goes here
        end for
    end else