Spaces:
Running
Running
| Write method | |
| int largestElement(ArrayList<Integer> numberse) | |
| which returns the largest of the elements in the integer list called numbers. | |
| Example method call: | |
| public static void main(String[] args) { | |
| ArrayList<Integer> testnumbers = new ArrayList<>(); | |
| testnumbers.add(4); | |
| testnumbers.add(9); | |
| testnumbers.add(3); | |
| testnumbers.add(-2); | |
| int largest = largestElement(testnumbers); | |
| System.out.println("Largest: " + largest); | |
| } | |
| Program outputs: | |
| Largest: 9 | |
| import java.util.Random; | |
| import java.util.ArrayList; | |
| import java.util.Arrays; | |
| import java.util.stream.Collectors; | |
| public class Test{ | |
| public static void main(String[] args){ | |
| final Random r = new Random(); | |
| test(new int[]{4,20,3,6,7,8,9,11,13,16,17}); | |
| test(new int[]{1,5,2,4,3,6,4,7,5,8,6,3,9,5,3}); | |
| test(new int[]{-5,-4,-1,-2,-3,-6,-7}); | |
| int length = r.nextInt(10) + 10; | |
| int[] l = new int[length]; | |
| for (int i=0; i<length; i++) { | |
| l[i] = (100 - r.nextInt(200)); | |
| } | |
| test(l); | |
| } | |
| public static void test(int[] l) { | |
| ArrayList<Integer> list = new ArrayList<>(); | |
| for (int a : l) { | |
| list.add(a); | |
| } | |
| System.out.println("Testing with list " + list); | |
| System.out.println("Largest element: " + largestElement(list)); | |
| System.out.println(""); | |
| } | |
| //ADD | |
| public static int largestElement(ArrayList<Integer> numbers) { | |
| int max=-999; | |
| for (int num: numbers) { | |
| if (num>max) { | |
| max = num; | |
| } | |
| } | |
| return max; | |
| } | |
| } | |
| Testing with list [4, 20, 3, 6, 7, 8, 9, 11, 13, 16, 17] | |
| Largest element: 20 | |
| Testing with list [1, 5, 2, 4, 3, 6, 4, 7, 5, 8, 6, 3, 9, 5, 3] | |
| Largest element: 9 | |
| Testing with list [-5, -4, -1, -2, -3, -6, -7] | |
| Largest element: -1 | |
| Testing with list [-18, 1, 41, 73, 60, 89, 14, -70, -8, -75, -14, -35, 78, 35, 36] | |
| Largest element: 89 | |