Spaces:
Running
Running
File size: 1,988 Bytes
320940e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 |
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
|