KaiquanMah commited on
Commit
59719c2
·
verified ·
1 Parent(s): 0e8ae4a

Create 6B. Create a list

Browse files
Week 3: Objects, files and exceptions/6B. Create a list ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Write the method
2
+
3
+ ArrayList<Integer> createList(int start, int end)
4
+
5
+ ...which takes as parameters the start and end values of the list.
6
+ The method generates a new list containing, in order, all the elements between the given points, one step apart.
7
+ As usual, the START sub-item is INCLUDED in the list, but the END sub-item IS NOT.
8
+
9
+ Note that the list must be created BACKWARDS IF the STARTING sub-item is GREATER than the ending sub-item.
10
+ See the sample performances for an example.
11
+
12
+
13
+ Examples on method calls:
14
+ public static void main(String[] parameters){
15
+ System.out.println(createList(1,10));
16
+ System.out.println(createList(10,1));
17
+ }
18
+
19
+ Program outputs:
20
+ [1, 2, 3, 4, 5, 6, 7, 8, 9]
21
+ [10, 9, 8, 7, 6, 5, 4, 3, 2]
22
+
23
+
24
+
25
+ ===============================
26
+
27
+
28
+
29
+ import java.util.Random;
30
+ import java.util.ArrayList;
31
+
32
+ public class Test{
33
+ public static void main(String[] args){
34
+ final Random r = new Random();
35
+
36
+
37
+ Object[][] p = {{1,4}, {100,106}, {5,0}, {90,80}};
38
+ for (Object[] pa : p) {
39
+ System.out.print("Testing with parameters ");
40
+ System.out.println(pa[0] + ", " + pa[1]);
41
+ System.out.println(createList((Integer) pa[0], (Integer) pa[1]));
42
+ System.out.println("");
43
+ }
44
+ }
45
+
46
+
47
+ public static ArrayList<Integer> createList(int start, int end) {
48
+ ArrayList<Integer> list = new ArrayList<>();
49
+ // ascending order
50
+ if (start < end) {
51
+ for (int i = start; i < end; i++) {
52
+ list.add(i);
53
+ }
54
+ }
55
+ // start > end
56
+ // descending order
57
+ // start >> start-1 >> ... >> (excluding) 'end'
58
+ else {
59
+ for (int i = start; i > end; i--) {
60
+ list.add(i);
61
+ }
62
+ }
63
+ return list;
64
+ }
65
+
66
+
67
+
68
+
69
+
70
+
71
+ }
72
+
73
+
74
+
75
+
76
+
77
+
78
+ Testing with parameters 1, 4
79
+ [1, 2, 3]
80
+
81
+ Testing with parameters 100, 106
82
+ [100, 101, 102, 103, 104, 105]
83
+
84
+ Testing with parameters 5, 0
85
+ [5, 4, 3, 2, 1]
86
+
87
+ Testing with parameters 90, 80
88
+ [90, 89, 88, 87, 86, 85, 84, 83, 82, 81]
89
+
90
+
91
+
92
+