Hey everyone im trying to grasp why this finds the smallest number the code was given to me earlier in the material and just copied it in but before moving on i would like to understand it here is the code
import java.util.ArrayList;
import java.util.Scanner;
public class IndexOfSmallest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// create an array list to hold input numbers
ArrayList<Integer> list = new ArrayList<>();
// read inputs from user until 9999 is entered
while (true) {
int input = Integer.valueOf(scanner.nextLine());
if (input == 9999) {
break;
}
// add the input to the array list
list.add(input);
}
// initialize index variable to first element in the array list
int index = list.get(0);
// loop through each element in the array list and find the smallest value
for (int i = 0; i < list.size(); i++) {
int number = list.get(i);
if (index > number) {
index = number;
}
}
// print out the smallest number
System.out.println("The smallest number: " + index);
// loop through each element in the array list and find the indices of the smallest number
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == index) {
// if the element matches the smallest value, print its index
System.out.println(index + " is at index " + i);
}
}
}
}