This program takes an array of numbers and then returns the largest number.
My Code
import java.util.ArrayList;
import java.util.Collections;
public class TheGreatest {
public static int greatest(ArrayList<Integer> list) {
// write code here
Collections.sort(list, Collections.reverseOrder());
return list.get(0);
}
public static void main(String[] args) {
ArrayList<Integer> lista = new ArrayList<Integer>();
lista.add(3);
lista.add(2);
lista.add(7);
lista.add(2);
System.out.println("The greatest number is: " + greatest(lista));
}
}
Model Code
import java.util.ArrayList;
public class TheGreatest {
public static int greatest(ArrayList<Integer> list) {
// write code here
// The first candidate for the greatest is the first in the list
int greatestSoFar = list.get(0);
// then we iterate over the whole list
for (int luku : list) {
// if a greater found, we take that as the candidate for greatest
if (luku > greatestSoFar) {
greatestSoFar = luku;
}
}
return greatestSoFar;
}
public static void main(String[] args) {
ArrayList<Integer> lista = new ArrayList<Integer>();
lista.add(3);
lista.add(2);
lista.add(7);
lista.add(2);
System.out.println("The greatest number is: " + greatest(lista));
}
}
Comments
I am quite happy with that. I didn’t want to go down the path of having to iterate the entire list so I just sorted it in reverse order and then returned list(0).