KaiquanMah commited on
Commit
3bf0ae7
·
verified ·
1 Parent(s): f5d4e7e

Create 10. Array from list

Browse files
Week 3: Objects, files and exceptions/10. Array from list ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Write the method
2
+
3
+ double[] newArray(ArrayList<Double> list)
4
+
5
+ which takes a list of floats as its parameter.
6
+ The method creates and returns a floating point array with the same elements in the same order as the list.
7
+
8
+ Example method call:
9
+
10
+ public static void main(String[] args){
11
+ ArrayList<Double> test = new ArrayList<>();
12
+ test.add(1.0);
13
+ test.add(3.0);
14
+ test.add(2.75);
15
+
16
+ double[] array = newArray(test);
17
+ System.out.println("Array: " + Arrays.toString(array));
18
+ }
19
+
20
+ Program outputs:
21
+ Array: [1.0, 3.0, 2.75]
22
+
23
+
24
+
25
+ ================
26
+
27
+
28
+ import java.util.Random;
29
+ import java.util.ArrayList;
30
+ import java.util.Arrays;
31
+
32
+ public class Test {
33
+ public static void main(String[] args) {
34
+ final Random random = new Random();
35
+
36
+
37
+ double[] decimalValues = {0, 0.25, 0.5, 0.75};
38
+
39
+ for (int testNumber = 1; testNumber <= 3; testNumber++) {
40
+ System.out.println("Test " + testNumber);
41
+ ArrayList<Double> list = new ArrayList<>();
42
+ int size = random.nextInt(5) + 5;
43
+ for (int i = 0; i < size; i++) {
44
+ double element = random.nextInt(10) + decimalValues[random.nextInt(decimalValues.length)];
45
+ list.add(element);
46
+ }
47
+
48
+ System.out.println("List: " + list);
49
+ double[] array = newArray(list);
50
+ System.out.println("Array: " + Arrays.toString(array));
51
+ System.out.println("");
52
+ }
53
+ }
54
+
55
+
56
+
57
+ // CONVERT LIST TO ARRAY
58
+ public static double[] newArray(ArrayList<Double> list) {
59
+ double[] array = new double[list.size()];
60
+ // for (int num: list) {
61
+ // array[i] = num;
62
+ // }
63
+
64
+ // for list - need to get element using idx
65
+ for (int i = 0; i < list.size(); i++) {
66
+ array[i] = list.get(i);
67
+ }
68
+ return array;
69
+ }
70
+
71
+
72
+ }
73
+
74
+
75
+
76
+
77
+
78
+
79
+
80
+ Test 1
81
+ List: [3.0, 6.25, 5.0, 4.75, 1.25, 8.75, 0.0, 7.0, 0.0]
82
+ Array: [3.0, 6.25, 5.0, 4.75, 1.25, 8.75, 0.0, 7.0, 0.0]
83
+
84
+ Test 2
85
+ List: [2.25, 9.75, 7.25, 2.25, 7.5, 5.25, 9.0, 8.75]
86
+ Array: [2.25, 9.75, 7.25, 2.25, 7.5, 5.25, 9.0, 8.75]
87
+
88
+ Test 3
89
+ List: [4.5, 5.75, 9.5, 5.0, 9.75]
90
+ Array: [4.5, 5.75, 9.5, 5.0, 9.75]
91
+
92
+
93
+
94
+