KaiquanMah commited on
Commit
9b478da
·
verified ·
1 Parent(s): 6a0d5f3

Create 17b. Count positive and negative elements

Browse files
Week 2: Methods, strings and lists/17b. Count positive and negative elements ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The program has a preformatted list variable numbers, which points to an integer-type list.
2
+ Your task is to count how many negative and how many positive elements there are in the list.
3
+ Print the result as shown in the example below:
4
+
5
+ Example execution:
6
+ Positives: 10
7
+ Negatives: 6
8
+
9
+
10
+
11
+
12
+ import java.util.Random;
13
+ import java.util.ArrayList;
14
+
15
+ public class Test{
16
+ public static void main(String[] args){
17
+ final Random rnd = new Random();
18
+
19
+
20
+ for (int test=1; test<=3; test++) {
21
+ System.out.println("Test number " + test);
22
+
23
+ // initialise an Integer list
24
+ ArrayList<Integer> numbers = new ArrayList<>();
25
+
26
+ // random int from 0 to 15 (excluding 15)
27
+ // add 10 to it: 10-24
28
+ int length = 10 + rnd.nextInt(15);
29
+
30
+ // for the 10-24 integers
31
+ // random int from 0 to 30 (excluding 30)
32
+ // each element = 15 - rand_int_0_uptobutnotincl30
33
+ for (int i=0; i<length; i++) {
34
+ numbers.add(15 - rnd.nextInt(30));
35
+ }
36
+
37
+ System.out.println("List: " + numbers);
38
+
39
+
40
+ //ADD
41
+ int pos=0;
42
+ int neg=0;
43
+ for (int num: numbers) {
44
+ if (num>0) {
45
+ pos++;
46
+ }
47
+ else if (num<0) {
48
+ neg++;
49
+ }
50
+ }
51
+
52
+ System.out.println("Positives: " + pos);
53
+ System.out.println("Negatives: " + neg);
54
+
55
+
56
+
57
+
58
+ System.out.println("");
59
+ }
60
+ }
61
+ }
62
+
63
+
64
+
65
+
66
+ Test number 1
67
+ List: [5, 7, 7, -13, 11, -13, 11, -3, -2, 6, 0, 14, 1, 13, -6, 6, -8, 15, -13, -10, 6]
68
+ Positives: 12
69
+ Negatives: 8
70
+
71
+ Test number 2
72
+ List: [-13, 6, 7, -7, 9, -6, 0, -7, -8, -13, 6, -9, -10, -10, -10, 10, -7, -2, -5, -8, 13, -8, 9, -12]
73
+ Positives: 7
74
+ Negatives: 16
75
+
76
+ Test number 3
77
+ List: [-14, 12, 15, 0, -2, -1, 7, 13, 14, 11, -4, 1, 9, 3, 1]
78
+ Positives: 10
79
+ Negatives: 4
80
+
81
+