I have a task to create a program using only for loop and math functions that input N amount of cars and each iteration gets the time it took the car to reach the end, the final output needs to be the first one to reach the end and the second, meaning the two lowest times.
I've created a program:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter total cars: ");
int cars = sc.nextInt();
double first = 0, second = 0;
int car1 = 1, car2 = 1;
for (int i = 1; i <= cars; i++) {
System.out.println("enter car number " + i + " speed:");
double speed = sc.nextDouble();
if (i == 1) {
first = speed;
second = speed;
}
if (speed < first) {
second = first;
first = speed;
car2 = car1;
car1 = i;
} else {
if (speed < second) {
car2 = i;
second = speed;
}
}
}
System.out.println("car number one is " + car1 +" with speed of " + first);
System.out.println("car number two is " + car2 +" with speed of " + second);
}
}
the problem I had is how to start the first and second var, as they cant be set to 0, because I need to check if the speed I get is lower than the first or the second. i tried maybe on the first iteration to set first and second to speed to have something to start with, but it still bugs, so I wondered how could I fix it? thanks ahead.
Here is the working code below that will let the user enter any number of cars, ask for their time taken, and then print the car number of the two lowest times and their respective time taken:
The important part is that you can initialize the time
double
values usingDouble.MAX_VALUE
in order to ensure the first 2 cars will always replace the initial values:Besides that the code honestly has the confusing variable names. I used longer names that have more meaning in order to make the code easier to understand.
Example Run: