Reputation: 49
I'm a beginner at java and was just wondering how to find the max and minimum value from integers declared in a for loop (using a scanner to obtain user input) this program creates an object from a class Car and obtains information on the name, registration, colour and number of trips.
The number of trips prompts the for loop to print out odometer readings from 0 (odometer's initial reading) to whatever the variable carSample.numberOfTrips specifies.
I've tried declaring a new variable; int maximum = carSample.odometerReading.MAX_VALUE; (Then printing it) aswell with minimum, however to no success; I receive the following error:
TestCar.java:25: error: int cannot be dereferenced int maximum = carSample.odometerReading.MAX_VALUE;
public static void main(String[] args){
Scanner input = new Scanner(System.in);
car carSample = new car(); // Creates object of class Car
carSample.name = input.nextLine();
carSample.registration = input.nextLine();
carSample.colour = input.nextLine();
carSample.numberOfTrips = input.nextInt();
for (int i = 0; i < carSample.numberOfTrips; i++) {
System.out.print("Odometer reading " + (i) + ": ");
int odometerReading = input.nextInt();
}
Any help or insight into how this can be peformed is really appreciated, thank you for your time!
Upvotes: 0
Views: 906
Reputation: 187
If readings are for example 20 10 22 41 11
Do the first reading. 20
And use that value as your maximum and also minimum. So maximum = 20 and minimum = 20.
Then for the other readings, compare the reading to the current maximum and minimum and update the maximum and minimum accordingly. E.g: second reading: 10. 10 is less than current maximum of 20, so no change in maximum. 10 is less than current minimum of 20, so update minimum to 10....and repeat for the remainder of the loop.
Upvotes: 2
Reputation: 105
int maximum = Integer.MIN_VALUE;
for (int i = 0; i < carSample.numberOfTrips; i++) {
System.out.print("Odometer reading " + (i) + ": ");
int odometerReading = input.nextInt();
if (odometerReading > maximum) {
maximum = odometerReading;
}
}
System.out.println(maximum); // Maximum value
Upvotes: 3