KaiquanMah commited on
Commit
320940e
·
verified ·
1 Parent(s): 9b478da

Create 18. Largest element

Browse files
Week 2: Methods, strings and lists/18. Largest element ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Write method
2
+
3
+ int largestElement(ArrayList<Integer> numberse)
4
+
5
+ which returns the largest of the elements in the integer list called numbers.
6
+
7
+
8
+ Example method call:
9
+ public static void main(String[] args) {
10
+ ArrayList<Integer> testnumbers = new ArrayList<>();
11
+ testnumbers.add(4);
12
+ testnumbers.add(9);
13
+ testnumbers.add(3);
14
+ testnumbers.add(-2);
15
+
16
+ int largest = largestElement(testnumbers);
17
+ System.out.println("Largest: " + largest);
18
+ }
19
+
20
+ Program outputs:
21
+ Largest: 9
22
+
23
+
24
+
25
+
26
+
27
+
28
+
29
+ import java.util.Random;
30
+ import java.util.ArrayList;
31
+ import java.util.Arrays;
32
+ import java.util.stream.Collectors;
33
+
34
+ public class Test{
35
+ public static void main(String[] args){
36
+ final Random r = new Random();
37
+
38
+ test(new int[]{4,20,3,6,7,8,9,11,13,16,17});
39
+ test(new int[]{1,5,2,4,3,6,4,7,5,8,6,3,9,5,3});
40
+ test(new int[]{-5,-4,-1,-2,-3,-6,-7});
41
+
42
+ int length = r.nextInt(10) + 10;
43
+ int[] l = new int[length];
44
+ for (int i=0; i<length; i++) {
45
+ l[i] = (100 - r.nextInt(200));
46
+ }
47
+ test(l);
48
+
49
+
50
+ }
51
+
52
+ public static void test(int[] l) {
53
+ ArrayList<Integer> list = new ArrayList<>();
54
+ for (int a : l) {
55
+ list.add(a);
56
+ }
57
+ System.out.println("Testing with list " + list);
58
+ System.out.println("Largest element: " + largestElement(list));
59
+ System.out.println("");
60
+ }
61
+
62
+
63
+ //ADD
64
+ public static int largestElement(ArrayList<Integer> numbers) {
65
+ int max=-999;
66
+ for (int num: numbers) {
67
+ if (num>max) {
68
+ max = num;
69
+ }
70
+ }
71
+ return max;
72
+ }
73
+
74
+
75
+
76
+ }
77
+
78
+
79
+
80
+
81
+
82
+
83
+
84
+
85
+
86
+ Testing with list [4, 20, 3, 6, 7, 8, 9, 11, 13, 16, 17]
87
+ Largest element: 20
88
+
89
+ Testing with list [1, 5, 2, 4, 3, 6, 4, 7, 5, 8, 6, 3, 9, 5, 3]
90
+ Largest element: 9
91
+
92
+ Testing with list [-5, -4, -1, -2, -3, -6, -7]
93
+ Largest element: -1
94
+
95
+ Testing with list [-18, 1, 41, 73, 60, 89, 14, -70, -8, -75, -14, -35, 78, 35, 36]
96
+ Largest element: 89
97
+
98
+
99
+
100
+
101
+