Q: Java code logic New to Java and using old MIT  course to self teach. Here's my code. It returns Thomas: 273
John: 243
Can anyone explain why it's returning two values rather than just the fastest runner?
public class Marathon {

    public static void main(String args[]) {
        String[] names = { "Elena", "Thomas", "Hamilton", "Suzie", "Phil", "Matt", "Alex", "Emma", "John", "James",
                "Jane", "Emily", "Daniel", "Neda", "Aaron", "Kate" };
        int[] times = { 341, 273, 278, 329, 445, 402, 388, 275, 243, 334, 412, 393, 299, 343, 317, 265 };
        int smallest = times[0]; // sets smallest to 341

        for (int x = 0; x < times.length; x++) {

            if (times[x] < smallest) {
                smallest = times[x];
                System.out.println(names[x] + ": " + times[x]);
            }
        }
    }
}


A: Because you are printing everytime you find a smaller value:
if (times[x] < smallest) {
    smallest = times[x];
    System.out.println(names[x] + ": " + times[x]); // print always
}

If you need to print only fastest, than you need to separate logic to find fastest and print the result.
int smallest = times[0]; // sets smallest to 341
for (int x = 0; x < times.length; x++) {
    if (times[x] < smallest) {
        smallest = times[x];
    }
}
System.out.println(names[smallest] + ": " + times[smallest]);


A: The issue with your code is that you output each time you find something that is smaller than "smallest".
You initialise smallest with first value in the times array, which is 341. Then on the first step of the loop it will be update from 341 to 243 and hence you will print Thomas.
Instead, you have to print after the loop.

A: From the way you have done it, you are printing every occurrence of when the if condition occurs which would be twice one for 273 and one for 243.
With this extra variable used you are saving the index at which the smallest was found and then accessing it from that. There are many ways of doing it though.
public static void main(String[] args) {
   String[] names = { "Elena", "Thomas", "Hamilton", "Suzie", "Phil", "Matt", "Alex", "Emma", "John", "James",
        "Jane", "Emily", "Daniel", "Neda", "Aaron", "Kate" };
   int[] times = { 341, 273, 278, 329, 445, 402, 388, 275, 243, 334, 412, 393, 299, 343, 317, 265 };
   int smallest = times[0]; // sets smallest to 341
   int index = 0;

   for (int x = 0; x < times.length; x++) {

       if (times[x] < smallest) {
           smallest = times[x];
           index = x;
       }
   }

   System.out.println(names[index] + ": " + times[index]);
}

